Customizing Webpack Config

For most apps, the default configuration of webpack is sufficient, but sometimes you need to tweak a setting in your webpack config. This guide explains how to make a small change without taking on the maintenance burden of the entire webpack config.

Angular

For Angular developers, use an executor like ngx-build-plus.

In your project.json configuration for the @nrwl/web:webpack or @nrwl/node:webpack executor, set the webpackConfig option to point to your custom webpack config file. i.e. apps/my-app/custom-webpack.config.js

The custom webpack file contains a function that takes as input the existing webpack config and then returns a modified config object. context includes all the options specified for the executor.

apps/my-app/custom-webpack.config.js:

1// Helper for combining webpack config objects
2const { merge } = require('webpack-merge');
3
4module.exports = (config, context) => {
5  return merge(config, {
6    // overwrite values here
7  });
8};
9

Also supports async functions

1// Utility function for sleeping
2const sleep = (n) => new Promise((resolve) => setTimeout(resolve, n));
3
4module.exports = async (config, context) => {
5  await sleep(10);
6  return merge(config, {
7    // overwrite values here
8  });
9};
10

Add a Loader

To add the css-loader to your config, install it and add the rule.

npm install -save-dev css-loader
1const { merge } = require('webpack-merge');
2
3module.exports = (config, context) => {
4  return merge(config, {
5    module: {
6      rules: [
7        {
8          test: /\.css$/i,
9          use: ['style-loader', 'css-loader'],
10        },
11      ],
12    },
13  });
14};
15

Module Federation

If you use the Module Federation support from @nrwl/angular or @nrwl/react then you can customize your webpack configuration as follows.

1const { merge } = require('webpack-merge');
2const withModuleFederation = require('@nrwl/react/module-federation');
3// or `const withModuleFederation = require('@nrwl/angular/module-federation');`
4
5module.export = async (config, context) => {
6  const federatedModules = await withModuleFederation({
7    // your options here
8  });
9
10  return merge(federatedModules(config, context), {
11    // overwrite values here
12  });
13};
14

Reference the webpack documentation for details on the structure of the webpack config object.

Next.js Applications

Next.js supports webpack customization in the next.config.js file.

1const { withNx } = require('@nrwl/next/plugins/with-nx');
2
3const nextConfig = {
4  webpack: (
5    config,
6    { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
7  ) => {
8    // Important: return the modified config
9    return config;
10  },
11};
12
13return withNx(nextConfig);
14

Read the official documentation for more details.

Concepts

Recipes

Reference