In Next.js, starting from version 10.0.5, Webpack 5 is used by default for building. If you are using this version or a higher version, Next.js automatically bundles your project with Webpack 5 without requiring any special configuration.
However, if you need to customize the Webpack configuration, Next.js provides a highly flexible approach to extend its default configuration. You can create a next.config.js file in the project root directory and use the webpack configuration function to modify the default settings.
Here is an example of customizing the Webpack configuration using a next.config.js file:
javascript// next.config.js module.exports = { future: { webpack5: true, // If you are using Next.js versions prior to 10.2, manually set this option to enable Webpack 5 support }, webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => { // Note: Avoid modifying references of input parameters, such as directly pushing content with `config.plugins.push()`, as it may cause reference errors. // Instead, use the spread operator or `Array.concat` to generate new arrays or objects. // Example: Adding a new plugin const newConfig = { ...config, plugins: [ ...config.plugins, new webpack.DefinePlugin({ 'process.env.VERSION': JSON.stringify(buildId), }), ], }; // Example: Modifying resolution options newConfig.resolve.alias = { ...config.resolve.alias, components: path.resolve(__dirname, 'src/components'), }; // Return the modified configuration return newConfig; }, };
In this configuration, the webpack function receives the current Webpack configuration object config and an object containing useful properties, then modifies the plugin list and resolution options. First, it adds a new DefinePlugin to define an environment variable. Next, it updates resolve.alias to include a new alias, which simplifies module import paths.
By doing this, you can adjust the Webpack configuration according to your project's specific needs to optimize both build and runtime performance.
Be mindful that directly modifying the config object reference may introduce unintended side effects; always use immutable updates to modify it. For example, employ the spread operator or functional programming methods like Array.concat.