Webpack not excluding node_modules
Solution 1:
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:
-
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. -
Set the
externalPresets
ofnode
totrue
. As of Webpack@5, This configuration will exclude native node modules (path, fs, etc.) from being bundled. -
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.
},
...
};
Solution 2:
If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true
in your tsconfig.json
file.
Solution 3:
Try use absolute path:
exclude:path.resolve(__dirname, "node_modules")