node-app-root-path icon indicating copy to clipboard operation
node-app-root-path copied to clipboard

Path resolution in npm linked modules report module and not root app path.

Open MarkGriffiths opened this issue 6 years ago • 6 comments
trafficstars

I only noticed this today when changes in globby starting throwing path errors, so might have been there a while and I just didn't notice.

Under node v11, working in an app with the following pattern:

./project/app/
./project/shared-lib-1/
./project/shared-lib-2/

app-root-path is used in each shared lib. When these are installed with npm install, the libs correctly report the app's root path. In development, when the libs are linked with npm link, app-root-path reports the root path of the lib module, not the app.

MarkGriffiths avatar Mar 04 '19 08:03 MarkGriffiths

The cause is using __dirname to resolve the root path.

If a module is linked while being used locally in an app, the __dirname in app-root-path may not overlap with the app's path.

It makes using npm link or yarn link quite a hassle. Is there an easy way to fix this, or perhaps app-root-path is simply not intended to be used in a NPM module?

stoicskyline avatar Apr 25 '19 23:04 stoicskyline

Ran into this issue in an npm module I was developing. It worked great when actually npm/yarn installed, but not when linked. I ended up just creating a workaround option in my package for project root. However, it'd be great if there was a fallback if linked to somehow get the running project's root.

harryhorton avatar Sep 23 '19 14:09 harryhorton

same issue here( Does not work when creating custom package for npm, it starts referring to the package project directory.

MetaMmodern avatar May 14 '21 14:05 MetaMmodern

I have to share an interesting bug that caused an outage and took me a long time to figure out and is directly related to this issue:

https://medium.com/@fagnerbrack/the-story-of-a-stupid-bug-that-is-impossible-to-reproduce-6863ac526172

Basically:

  1. NPM install on local files creates a symlink.
  2. Zipping removes the symlink.
  3. This can cause a bug with tools like app-root-path that uses _dirname which can only happen in prod and is impossible to reproduce locally.

Exactly like what @jorgechen said.

FagnerMartinsBrack avatar Jun 18 '21 03:06 FagnerMartinsBrack

Same problem with pnpm workspaces.

Temporarily, I solved the issue by defining a APP_ROOT_PATH environment var.

"scripts": {
  "dev": "APP_ROOT_PATH=`pwd` my-dev-command"
}

ByScripts avatar Nov 07 '21 16:11 ByScripts

I've been trying to find a solution for this, but it's not straightforward. The best non-custom workaround for my use case is the INIT_CWD environment variable, but this assumes that you ran a script with npm run (or variant, like pnpm run).

gtbuchanan avatar Jul 10 '24 16:07 gtbuchanan