How to change webpack config dynamically for each entry?

65 views Asked by At

Is there a way to hook into compilation process and overwrite webpack resolve.alias config for every entry during the compilation?

I have tried to come up with a custom plugin, but there's no documentation how to access and overwrite config. Here's what I have:

// webpack.config.js
module.exports = {
  ...
  resolve: {
    alias: {
      static: './x',
    },
  },
  plugins: [new MyPlugin()],
}

class MyPlugin {
  apply(compiler) {
    compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
      compilation.hooks.buildModule.tap('MyPlugin', (module) => {
        // I guess here I could do an overwrite, But how?
        //
        // I need to conditionally overwrite `resolve.alias.static`
        // based on the entry. Considering the entry is also dynamic.
        // if (module.filepath.includes('xyz')) {
        //   webpack.config.resolves.alias.public = 'y';
        // } else if (module.filepath.includes('abc')) {
        //   webpack.config.resolves.alias.public = 'z';
        // } else {
        //    use default from the initial webpack.config.js
        // }
      });
    });
  }
}

I have tried to play with various hooks from compilation-hooks, but maybe I'm using wrong hooks? Or just was not able to find documentation explaining how to hook into the config...

When webpack compiles the entry from packages/xyz/__tests__/CreateTask.test.tsx, I need one static alias is setup, when from another package — another alias is setup for compilation.

1

There are 1 answers

0
Afaq Ali Shah On

You can use a custom plugin and the resolve configuration options in Webpack to conditionally overwrite resolve.alias for different entry points during compilation.

// webpack.config.js
module.exports = {
  // ...
  resolve: {
    alias: {
      static: './x', // Default alias
    },
  },
  plugins: [new MyPlugin()],
}

class MyPlugin {
  apply(compiler) {
    compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
      compilation.hooks.buildModule.tap('MyPlugin', (module) => {
        // Get the module's filepath
        const moduleFilePath = module.resource;

        // Determine the condition based on the entry point
        let aliasToUpdate = 'static'; // Default alias
        if (moduleFilePath.includes('packages/xyz/')) {
          aliasToUpdate = 'xyz-alias'; // Alias for 'xyz' entry point
        } else if (moduleFilePath.includes('packages/abc/')) {
          aliasToUpdate = 'abc-alias'; // Alias for 'abc' entry point
        }

        // Update the alias based on the condition
        const resolveConfig = compilation.compiler.options.resolve;
        resolveConfig.alias.static = aliasToUpdate;
      });
    });
  }
}

Make sure you have appropriate alias configurations for 'xyz-alias' and 'abc-alias' in your Webpack configuration or elsewhere in your code.