我正在使用 webpack 作为我正在构建的 Node 框架(尽管我应该承认,我应该使用 gulp)。当我包含 EJS 模块时,webpack 将其包含在编译的源代码中,即使我明确告诉它排除 node_modules 目录。
module.exports = {
context: __dirname,
target: 'node',
// ...
output: {
libraryTarget: 'commonjs'
// ...
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader?{ "stage": 0, "optional": ["runtime"] }'
}
]
}
};
正如你所看到的,我对 JS 文件进行了测试,并告诉它排除 node_modules;为什么它忽略我的排除?
从你的配置文件来看,你似乎只是排除了node_modules
从被解析为babel-loader
, but not免遭捆绑。
为了排除node_modules
和本机节点库捆绑,您需要:
-
Add target: 'node'
给你的webpack.config.js
。这将把 NodeJs 定义为包应该运行的环境。对于 webpack,它改变了块加载行为、可用的外部模块和生成的代码风格(即使用require()
对于 NodeJs)它在捆绑期间使用。
-
Set the externalPresets
of node
to true
。从 Webpack@5 开始,此配置将排除本机节点模块 https://webpack.github.io/docs/configuration.html#target(路径、文件系统等)免于捆绑。
-
Use webpack-node-externals https://www.npmjs.com/package/webpack-node-externals为了排除其他node_modules
.
所以你的结果配置文件应该是这样的:
var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
target: 'node', // use require() & use NodeJs CommonJS style
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
externalsPresets: {
node: true // in order to ignore built-in modules like path, fs, etc.
},
...
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)