在模块中使用npm3无法获取父节点模块

不知道这是npm3一个已知问题,但由于npm3的扁平模块结构,从一个模块内,我不能findnode_modules使用,

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

相反,我必须使用,

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

遍历find它。 由于node_modules嵌套在包中,这显然不会发生在npm2 +上。

有没有解决的办法 ? 我search了每一个更好的解决scheme。

这可能是一个糟糕的devise。 我不知道为什么你需要手动定位node_modules ; 如果您确定已经安装了某些东西,请使用require.resolve()内buildrequire.resolve() ,为您find该包。 请注意,您可以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; }) 

然后在webpackconfiguration中:

 externals: nodeModules,