Bundling non-native npm modules with Webpack

Viewed 133

Description

I have a nodejs + TypeScript + express project and currently the source *.ts files are being bundled with webpack and node_modules is ignored with webpack-node-externals.

When I deploy bundle.js in Docker, I would need to still run npm i --production on the target image to install the dependencies, which installs all the modules listed in package.json

The Problem:

If I am using only one function from lodash which does not have native parts, the whole lodash module (4.8MB) is installed nonetheless (which is intended).

This results in a huge node_modules folder where functions inside packages aren't always necessarily used in bundle.js. This problem is especially prevalent when containerizing the application with Docker.

Is there any way to bundle non-native modules with Webpack while leaving native modules alone?

1 Answers

This is very similar to https://stackoverflow.com/a/54393299/2234013 - I believe you're looking for nodeExternals({ whitelist }) and babel-loader exclude:

  // excerpt from https://stackoverflow.com/a/54393299/2234013
  externals: [
    nodeExternals({
      whitelist: [/lodash/] 
    })
  ],
  ...
  module: {
    rules: [
      {
        ...
        exclude: /node_modules\/(?!(lodash).*/,
        use: {
          loader: 'babel-loader',
          ...
        }
      }
    ]
  }
Related