簡體   English   中英

告訴 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_modules 中找到它。 復制它,我的包中的相對導入從嵌套的包中導入。 這給我帶來了一些問題。 我如何正確配置它?

這是一個試圖澄清的草圖:

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_modules 而不是 root 導入 thied_pa​​ckage 文件。 我的包文件是用 babel 編譯成 dist/lib

謝謝你。

這里包,my_package 的json

{
  "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 安裝算法,當我安裝我的包時,它會將其 package.json 文件中列出的所有依賴項安裝到 node_modules 樹的最右側。

在我的情況下,問題是因為第三個包嵌套在我的包中,而項目根節點 node_modules 文件夾中的第三個包有不同的版本。 所以這兩個顯然都安裝了。

實際上,節點導入算法,如從 node_modules 文件夾加載中所述,在更嵌套的 node_modules 文件中搜索導入/需要的包,如果沒有找到,則繼續到項目的根目錄。 直到找到為止。

在我的情況下,我的包導入的第三個包文件位於其本地 node_modules 文件夾中。

為了規避這種行為,可以使用不同的解決方案:

  1. 模塊別名
  2. webpack 解析
  3. babel 插件解析器

是否可以探索它們以定義自定義導入行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM