告诉 npm 包从安装它的项目根目录 node_modules 导入

Tell npm package to import from project root node_modules where it is installed

我创建了一个 npm 包,我想将它安装到另一个项目中。

所以我进入项目的根文件夹并执行 npm install /path/to/package/folder

它正确安装了它(根据文档创建了一个符号链接)并且我可以使用它,从它作为经典导入 node_module。

我的问题是我创建的包内的相对导入。该包依赖于其他库和相关的 node_modules 文件夹。

碰巧我的包中的文件是从相对 node_modules 文件夹而不是项目根目录 node_modules 导入的。 如果我在我的根项目文件夹中安装了依赖项,我也会在我的包的嵌套 node_module 中找到它。复制它,我的包中的相对导入从嵌套的包中导入。这给我带来了一些问题。我该如何正确配置它?

这里有一个草图试图澄清:

my_project
    |
    |
     __ node_modules (root)
             |
             |
             my_package (in this case symlink to my package)
             |        |
             |        |
             |        |__node_modules  (nested) <-------
             |        |        |
             |        |        |
             |        |        |__ third_package
             |        |
             |        | 
             |        |__ dist
             |             |
             |             |
             |              __ lib
             |                  |
             |                  |
             |                  |__ index.js
             |
             |
             |___ third_package

index.js 从嵌套的 node_module 而不是根导入 thied_package 文件。 我的包文件是用 babel 编译成 dist/lib

谢谢。

这里包,json of my_package

{
  "name": "my_package",
  "version": "1.0.0",
  "description": "",
  "main": "lib/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "./node_modules/.bin/babel src --out-dir lib --copy-files",
  },
  "keywords": [
  ],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/cli": "^7.10.5",
    "@babel/core": "^7.11.4",
    "@babel/preset-env": "^7.11.0",
    "@babel/preset-react": "^7.10.4",
    "@fortawesome/fontawesome-free": "^5.14.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.30",
    "@fortawesome/free-brands-svg-icons": "^5.14.0",
    "@fortawesome/free-regular-svg-icons": "^5.14.0",
    "@fortawesome/free-solid-svg-icons": "^5.14.0",
    "@fortawesome/react-fontawesome": "^0.1.11",
    "leaflet": "^1.6.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-leaflet": "^2.7.0"
  },
  "peerDependencies": {
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-leaflet": "^2.7.0",
    "leaflet": "^1.6.0"
  },
  "devDependencies": {
    "babel-eslint": "^10.1.0",
  }
}

经过更多研究,

根据 npm installing algorithm,当我安装我的包时,它将安装其 package.json 文件中列出的所有依赖项,最右边是 node_modules 树的顶部。

在我的案例中,问题出现在我的包中 third_package 和项目根 node_modules 文件夹中的 third_package 有不同的版本。所以很明显两者都安装了。

确实,节点导入算法,如 loading from node_modules folder 中所述,在更嵌套的 node_modules 文件夹中搜索 imported/required 包,如果找不到,则继续到根目录的项目。直到找到为止。

在我的例子中,我的包导入的第三个包文件在其本地 node_modules 文件夹中找到。

要避免此行为,可以使用不同的解决方案:

  1. module alias
  2. webpack resolve
  3. babel plugin resolver

是否可以探索它们以定义自定义导入行为。