最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - How to use local node_modules and .mjs script from somewhere else - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question asked Nov 18, 2024 at 13:50 Jeanluca ScaljeriJeanluca Scaljeri 29.3k66 gold badges235 silver badges383 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Short 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.
发布评论

评论列表(0)

  1. 暂无评论