Ariful Haque
Ariful Haque

Reputation: 3750

Webpack multiple bundle based on configuration

I've worked with Webpack a little. I know who to do multiple bundles depends on multiple entry points, but I have a new situation.

One of our projects has a single codebase for 3 different countries (3 different URL and different URL structure). We have set of common codes and codes for C1, C2, C3. I want to run a single build and compile the ES6 code in 2 different files, like

app-common.js, c1-common.js, c2-common.js, c3-common.j2

Or

c1-app.js, c2-app.js, c3-app.js which will have common and specific js code baesd on configuration, like which files I want to bind with which bundle.

Is there any existing way to do it or how this can be achieved?

Upvotes: 0

Views: 427

Answers (1)

Andrei Duca
Andrei Duca

Reputation: 392

You could create a single point-of-entry file for your localized code and do conditional require statements based on a custom environment variable. Then set that up in your webpack config:

new webpack.DefinePlugin({
    'process.env.COUNTRY_CODE': 'fr'
}),

Then in your code:

let i18n_config;
const country = process.env.COUNTRY_CODE || 'en';

if (country === 'en') {
    i18n_config = require("./i18n/en.js");
}
if (country === 'fr') {
    i18n_config = require("./i18n/fr.js");
}

You can go even further and use an aggressive minifier to remove dead code:

const isEN = country === 'en';
const isFR = country === 'fr';

if (isEN) {
    i18n_config = require("./i18n/en.js");
}
if (isFR) {
    i18n_config = require("./i18n/fr.js");
}
// ... and so on

Your if statements will compile to if (true) {...} or if (false) {...}. The false block will be considered dead-code and will be removed by the minifier.

Upvotes: 2

Related Questions