Webpack 不排除 node_modules

Webpack not excluding node_modules

我正在将 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;为什么忽略我的排除?

尝试使用绝对路径:

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

从您的配置文件来看,您似乎只是将 node_modules 排除在 babel-loader 解析之外, 而不是 被捆绑。

为了从捆绑中排除 node_modules 和本机节点库,您需要:

  1. target: 'node' 添加到您的 webpack.config.js。这会将 NodeJs 定义为包应该 运行 所在的环境。对于 webpack,它更改了它在捆绑期间使用的块加载行为、可用的外部模块和生成的代码样式(即对 NodeJs 使用 require())。

  2. nodeexternalPresets设为true。从 Webpack@5 开始,此配置将 exclude native node modules (path, fs, etc.) 从被捆绑。

  3. 使用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. 
    },
    ...
};

如果您在使用 TypeScript 时 运行 遇到这个问题,您可能需要在 tsconfig.json 文件中添加 skipLibCheck: true

这对我有用:

排除:[/bower_components/, /node_modules/]

module.loaders

一组自动应用的加载器。

每个项目都可以具有这些属性:

测试:必须满足的条件

排除:不能满足的条件

包括:必须满足的条件

loader:一串“!”分开的装载机

loaders:加载器数组作为字符串

条件可以是正则表达式、绝对路径开头或其中之一与 "and" 组合的数组。

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

尝试以下解决方案:

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