node.js - 防止 require(...) 在父目录中查找模块

标签 node.js node-modules

我的 Node 项目的根目录所在的目录本身就是另一个 Node 项目的根目录。所以这两个文件夹都包含 package.jsonnode_modules。问题是在内部项目中,有时我 require 模块没有安装在这个项目中。但是 Node 只是默默地在父项目的 node_modules 中找到它们,这会导致令人讨厌的惊喜。我能以某种方式阻止它这样做吗?我不想更改项目的目录结构,除非它是唯一的解决方案。

最佳答案

Node 尝试解析当前模块路径名并将 node_modules 连接到它的每个父目录。 [Source] .

您可以在项目模块的顶部覆盖此方法,并添加一些逻辑以从结果路径数组中排除父目录。

//app.js <-- parent project module, should be added at the top

var Module = require('module').Module;
var nodeModulePaths= Module._nodeModulePaths; //backup the original method

Module._nodeModulePaths = function(from) {
    var paths = nodeModulePaths.call(this, from); // call the original method

    //add your logic here to exclude parent dirs, I did a simple match with current dir
    paths = paths.filter(function(path){
        return path.match(__dirname)
    })
    return paths;
};

灵感来自 this module

关于node.js - 防止 require(...) 在父目录中查找模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32455431/

相关文章:

javascript - babel-preset-es2016 需要 babel-runtime 的对等体,但没有安装

node.js - Ejs input_field_tag方法设置type属性为5

node.js - header 崩溃应用程序并出现错误 TypeError : undefined not an object (evaluating 'theme.label' )

php - 如何从 friend 表中获取 friend 列表以及我 friend 的 friend 数量

linker - 静态链接不适用于节点模块

npm - 将 Gatsby v4 升级到 v5

bitbucket - package.json 中带有版本的私有(private) bitbucket 存储库

node.js - 从 Mongoose 的两个集合中映射和获取数据

python - 为什么越来越,gyp ERR!堆栈错误 : Can't find Python executable "python"?

javascript - 使用 ES5 语法在 Node 中混合默认和命名导出