Webpack 不排除 node_module

我正在构建一个 Node 框架,使用的是 webpack (不可否认,我可能应该使用 Gulp)。当我包含 EJS 模块时,webpack 将它包含在编译后的源代码中,尽管我明确告诉它排除 node _ module 目录。

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 _ module; 为什么它忽略我的排除呢?

153959 次浏览

Try use absolute path:

exclude:path.resolve(__dirname, "node_modules")

From your config file, it seems like you're only excluding node_modules from being parsed with babel-loader, but not from being bundled.

In order to exclude node_modules and native node libraries from bundling, you need to:

  1. Add target: 'node' to your webpack.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. uses require() for NodeJs) it uses during bundling.

  2. Set the externalPresets of node to true. As of Webpack@5, This configuration will exclude native node modules (path, fs, etc.) from being bundled.

  3. Use webpack-node-externals in order to exclude other 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.
},
...
};

If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true in your tsconfig.json file.

This worked for me:

exclude: [/bower_components/, /node_modules/]

module.loaders

A array of automatically applied loaders.

Each item can have these properties:

test: A condition that must be met

exclude: A condition that must not be met

include: A condition that must be met

loader: A string of "!" separated loaders

loaders: A array of loaders as string

A condition can be a RegExp, an absolute path start, or an array of one of these combined with "and".

See http://webpack.github.io/docs/configuration.html#module-loaders

try this below solution:

exclude:path.resolve(__dirname, "node_modules")