Configure node externals in a NodeJS code that bundles React code
Scenario
In most cases, we bundle TypeScript/JavaScript code to run in NodeJS only when we are doing SSR with a frontend library such as React. We generally use webpack-node-externals
to create a JS bundle that will be run inside NodeJS. We use webpack-node-externals
to avoid including installed packages from node_modules
. Excluding node_modules from the bundle has benefits explained here.
Problem
Suppose the developer is using a pacakge such as d3-shape
(recharts
package has d3-shape
as it's dependency) which has ES modules instead of commonjs. Such packages cannot run in NodeJS until processed with a transpiler such as babel
. We have to transpile and include d3-shape
in the bundle, but, we won't be able to do it until we allow it specifically in the webpack-node-externals
's configuration (using the allowlist
option in the configuration). This will solve the problem but then we will have to keep on adding packages to the allowlist
.
Solution
We generally run two separate webpack builds for NodeJS:
One for code containing the React app. In this webpack configuration we DON'T use
webpack-node-externals
.One for the code that has
express
server or any other package that should not be included in the bundles (packages with dependency on NodeJS extension). In this webpack configuration we usewebpack-node-externals
.