Webpack 不排除 node_modules [英] Webpack not excluding node_modules

查看:116
本文介绍了Webpack 不排除 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:

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

  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.

nodeexternalPresets设置为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆