Easily exclude node modules in Webpack
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
This library creates an externals function that ignores
node_modules when bundling in Webpack.
(Inspired by the great Backend apps with Webpack series)
npm install webpack-node-externals --save-dev
var nodeExternals = ;...moduleexports =...target: 'node' // in order to ignore built-in modules like path, fs, etc.externals: // in order to ignore all modules in node_modules folder...;
And that's it. All node modules will no longer be bundled but will be left as
This library scans the
node_modules folder for all node_modules names, and builds an externals function that tells Webpack not to bundle those modules, or any sub-modules of theirs.
This library accepts an
An array for the
externals to whitelist, so they will be included in the bundle. Can accept exact strings (
'module_name'), regex patterns (
/^module_name/), or a function that accepts the module name and returns whether it should be included.
Important - if you have set aliases in your webpack config with the exact same names as modules in node_modules, you need to whitelist them so Webpack will know they should be bundled.
The method in which unbundled modules will be required in the code. Best to leave as
commonjs for node modules.
The folder in which to search for the node modules.
Read the modules from the
package.json file instead of the
var nodeExternals = ;...moduleexports =...target: 'node' // important in order not to bundle built-in modules like path, fs, etc.externals:...;
For most use cases, the defaults of
modulesDir should be used.
Webpack allows inserting regex in the externals array, to capture non-relative modules:
externals:// Every non-relative module is external// abc -> require("abc")/^[a-z\-0-9]+$/
However, this will leave unbundled all non-relative requires, so it does not account for aliases that may be defined in webpack itself.
This library scans the
node_modules folder, so it only leaves unbundled the actual node modules that are being used.
whitelist option, this is possible. We can simply tell Webpack to bundle all files with extensions that are not js/jsx/json, using this [regex](https://regexper.com/#%5C.(%3F!(%3F%3Ajs%7Cjson)%24).%7B1%2C5%7D%24):
Thanks @wmertens for this idea.
Contributions and pull requests are welcome. Please run the tests to make sure nothing breaks. ### Test
npm run test