【问题标题】:npm: cannot find module which exists in node_modulesnpm:找不到 node_modules 中存在的模块
【发布时间】:2017-11-04 22:17:38
【问题描述】:

假设 JS 应用程序 A 导入了几个公共 npm 模块。假设 B 就是这样一个模块。

// ./A/index.js
import B from B;

我转到 ./node_modules/B 并通过在 B 的 package.json 中添加一个新依赖项来修改其源代码,比如 C,我将其导入 B 中

// ./node_modules/B/index.js
import C from C;

然后我在 ./node_modules/B 内运行 npm install ,这会在 ./node_modules/B 内创建另一个 node_modules 目录

当我运行 A 时,会出现类似

的错误
Error: Could not find module C imported from B

我做错了什么? 在我为 PR 打包之前测试现有公共模块的更改的最佳方法是什么?

【问题讨论】:

    标签: node.js npm


    【解决方案1】:

    你做得对,可能模块 C 不存在,你有两种方法,第一种是你现在做的方式(安装在 node_modules 中),第二种:使用require.resolve,检查下面的示例

    在 node_modules 中安装时的示例演示

    index.js

    import yn from 'yn'; // sample lib for detecting yes/no
    console.log(yn('yes'));
    

    ./node_modules/yn/下面运行

    npm install ccount --save //sample lib for counting symbols
    

    ./node_modules/yn/index.js

    //.. omitted
    const ccount = require('ccount');
    console.log(ccount('123', '1'));
    //.. omitted
    

    结果

    ❯ node ./index.js 
    1
    true
    

    在当前目录安装时的示例演示

    index.js

    import yn from 'yn'; // sample lib for detecting yes/no
    console.log(yn('yes'));
    

    在根目录下运行(./index.js 所在的位置)

    npm install ccount --save //sample lib for counting symbols
    

    ./node_modules/yn/index.js

    //.. omitted
    const ccount = require(require.resolve('ccount', {paths: ['../../node_modules/ccount']}));
    console.log(ccount('123', '1'));
    //.. omitted
    

    结果

    ❯ node ./index.js 
    1
    true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2020-07-08
      • 2018-03-18
      相关资源
      最近更新 更多