gpt4 book ai didi

node.js - 在模块中使用 npm3 无法获取父 node_modules

转载 作者:太空宇宙 更新时间:2023-11-04 00:39:56 25 4
gpt4 key购买 nike

不确定这是否是 npm3 的已知问题,但由于 npm3 的扁平模块结构,在模块内,我无法使用以下方式找到 node_modules:

var node_modules = fs.readdirSync('node_modules'); 

相反,我必须使用,

var node_modules = fs.readdirSync('../../node_modules');

向上遍历找到它。这显然不会发生在 npm2+ 上,因为 node_modules 嵌套在包中。

有办法解决这个问题吗?我到处寻找更好的解决方案。

最佳答案

这可能是一个糟糕的设计。我不知道为什么你需要手动找到node_modules;如果您确定已安装某些内容,请使用内置的 require.resolve() 来为您找到该包。请注意,您不仅可以require.resolve() .js 文件,还可以package.json 所需包的文件,这有助于定位已安装包的根目录。

编辑:

如果您尝试使用 webpack 捆绑服务器代码,您可以手动定义外部:

var nodeModules = {};
fs.readdirSync('node_modules') // this always exists
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
})

然后在 webpack 配置中:

externals: nodeModules,

关于node.js - 在模块中使用 npm3 无法获取父 node_modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37297613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com