Webpack 不排除 node_modules [英] Webpack not excluding node_modules
问题描述
我正在将 webpack 用于我正在构建的 Node 框架(尽管我可能应该使用 gulp,无可否认).当我包含 EJS 模块时,webpack 会将它包含在编译源中,即使我明确告诉它排除 node_modules 目录.
I'm using webpack for a Node framework that I'm building (though I should probably use gulp, admittedly). When I include the EJS module, webpack includes it in the compiled source, even though I explicitly tell it to exclude the node_modules dir.
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;为什么它忽略了我的排除?
As you can see, I have a test for JS files, and I tell it to exclude node_modules; why is it ignoring my exclude?
推荐答案
从您的配置文件来看,您似乎只是将 node_modules
排除在 babel-loader解析之外代码>,但不是被捆绑.
From your config file, it seems like you're only excluding node_modules
from being parsed with babel-loader
, but not from being bundled.
为了从捆绑中排除 node_modules
和本机节点库,您需要:
In order to exclude node_modules
and native node libraries from bundling, you need to:
将
target: 'node'
添加到您的webpack.config.js
.这会将 NodeJs 定义为包应该运行的环境.对于 webpack,它改变了它在打包期间使用的块加载行为、可用的外部模块和生成的代码样式(即使用require()
for NodeJs).
Add
target: 'node'
to yourwebpack.config.js
. This will define NodeJs as the environment in which the bundle should run. For webpack, it changes the chunk loading behavior, available external modules and generated code style (ie. usesrequire()
for NodeJs) it uses during bundling.
将node
的externalPresets
设置为true
.从 Webpack@5 开始,此配置将 排除本机节点模块(路径、fs等),以免被捆绑.
Set the externalPresets
of node
to true
. As of Webpack@5, This configuration will exclude native node modules (path, fs, etc.) from being bundled.
使用 webpack-node-externals 以排除其他node_modules
.
所以你的结果配置文件应该是这样的:
So your result config file should look like:
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.
},
...
};
这篇关于Webpack 不排除 node_modules的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!