How to create two build using different config in different build folder in Next js?

191 Views Asked by At

Implementing "sidecar" pattern in Next js project for micro frontend integration.

Using Next js 13.

How to create two builds(one for a standalone application and the second for an MFE application) using different next.config.js files in different folders in Next js?

Using next-mf for module federation

code for web pack inside next.config.js

webpack: (config, options) => {
        config.resolve.fallback = { fs: false };
        if (!options.isServer) {
            config.plugins.push(
                new NextFederationPlugin({
                    name: 'demoapp',
                    filename: 'static/chunks/demoapp.js',
                    exposes: {
                        'demo-component':
                            'src/components/mfe/demo.tsx',
                    },
                    shared: {
                        react: {
                            singleton: true,
                            requiredVersion: false,
                            eager: true,
                        },
                        'react-dom': {
                            singleton: true,
                            requiredVersion: false,
                            eager: true,
                        },
                        
                    },
                    extraOptions: {
                        debug: true,
                    },
                }),
            );
        }
        return config;
    },
1

There are 1 best solutions below

1
On

To create two different builds using different configurations and output them to different build folders in Next.js, you can use environment variables and modify the distDir configuration in your next.config.js file.

Here's an example of how you can do this:

  1. Create two scripts that set an environment variable:
# build-prod.sh
export NEXT_PUBLIC_CONFIG=prod
next build

# build-dev.sh
export NEXT_PUBLIC_CONFIG=dev
next build

  1. Use the environment variable in your next.config.js file to set the distDir configuration:
// next.config.js
const config = {
  // Other configurations...
  distDir: process.env.NEXT_PUBLIC_CONFIG === 'prod' ? '.next-prod' : '.next-dev',
};

module.exports = config;

In this example, the build-prod.sh and build-dev.sh scripts set the NEXT_PUBLIC_CONFIG environment variable to 'prod' and 'dev' respectively, and then run next build. The next.config.js file checks the value of NEXT_PUBLIC_CONFIG and sets the distDir configuration to '.next-prod' or '.next-dev' based on its value.

Please replace 'prod', 'dev', '.next-prod', and '.next-dev' with the actual values you want to use.

To run the build-prod.sh or build-dev.sh script, you can use the bash command:

bash build-prod.sh
# or
bash build-dev.sh

This will run next build with the specified configuration and output the build to the specified directory.