I have a project that works fine when I have:
/project
my-script.mjs
node_modules
....
And execute it as follows
$> node ./my-script.mjs
However, the actual case is that my script is located outside of the project:
/scripts
my-script.mjs
/project
node_modules
....
So I do then
$> NODE_PATH=$(pwd)/node_modules node ../scripts/my-script.mjs
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'ts-morph' imported from ...
Inside my-script.mjs
I have the following import
import { Project, SyntaxKind } from 'ts-morph'
and ts-morph
is installed in that node_modules folder. Any sugegstions how I can fix this?
I have a project that works fine when I have:
/project
my-script.mjs
node_modules
....
And execute it as follows
$> node ./my-script.mjs
However, the actual case is that my script is located outside of the project:
/scripts
my-script.mjs
/project
node_modules
....
So I do then
$> NODE_PATH=$(pwd)/node_modules node ../scripts/my-script.mjs
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'ts-morph' imported from ...
Inside my-script.mjs
I have the following import
import { Project, SyntaxKind } from 'ts-morph'
and ts-morph
is installed in that node_modules folder. Any sugegstions how I can fix this?
1 Answer
Reset to default 1Short Answer: You can't.
Node.js's module resolution algorithm works by taking the current working directory, splitting it into components, and joining node_modules
to the end. For example, given /Users/user/projects/foo
, the following folders are available to place your node_modules
folder: /node_modules
, /Users/node_modules
, /Users/user/node_modules
, /Users/user/projects/node_modules
, and /Users/user/projects/foo/node_modules
.
You can't really place a directory outside those locations, as Node won't know to look there.
Personally, I'd stick with keeping it the way you had initially (put my-script.mjs
in the root), or else make a scripts
and a src
folder in project
if you want to keep them separate. You could also just install the dependencies of scripts
separately.
Long answers: If, for some reason, this directory structure is out of your control, here are some other options:
- Use a custom loader. I've never needed this in practice, have no idea how to do this, but it's there for use-cases like these.
- Symlink
../project/node_modules
to./node_modules
.ln -s ../project/node_modules ./node_modules
should do the trick on UNIX systems (macOS, Linux). On Windows, symlinks are more hassle than they're worth.