Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack not excluding 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"] }'             }         ]     } }; 

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?

like image 411
ndugger Avatar asked Oct 07 '15 19:10

ndugger


People also ask

Does Webpack exclude node_modules?

Webpack node modules externals. Webpack allows you to define externals - modules that should not be bundled. When bundling with Webpack for the backend - you usually don't want to bundle its node_modules dependencies. This library creates an externals function that ignores node_modules when bundling in Webpack.

Does Webpack include node_modules?

Webpack builds a dependency graph used internally Now all modules that are used in your app are included in the dependency graph. Your project have many installed dependencies in the node_modules folder that should not be included in your client-side JavaScript production bundle.


2 Answers

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.      },     ... }; 
like image 157
lyosef Avatar answered Oct 21 '22 21:10

lyosef


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

like image 29
mattnedrich Avatar answered Oct 21 '22 23:10

mattnedrich