【问题标题】:Prevent require(...) from looking up modules in the parent directory防止 require(...) 在父目录中查找模块
【发布时间】:2015-12-03 23:58:26
【问题描述】:

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

【问题讨论】:

  • Require 不会遍历路径树。你能发布你的文件结构吗?
  • 这不是你的文件夹结构。
  • @BrandonSmith 会向上遍历,但前提是在当前目录下找不到模块
  • 因为人会犯错?

标签: node.js node-modules


【解决方案1】:

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

【讨论】:

  • 现在,在 2018 年第四季度,它仍然是禁用 Nodejs 中的文件夹行走的唯一方法吗?我在我的 TypeScript monorepo 中需要它......
  • @Marecky:您至少可以通过在 tsconfig.json 中添加以下内容来更改 typescript 类型查找的行为:"typeRoots" : ["./node_modules/@types"]
  • ES6 导入有类似的东西吗?
猜你喜欢
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 2012-05-29
  • 1970-01-01
  • 2012-02-07
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多