user7597670
user7597670

Reputation:

pass variable to webpack to build different bundle

I am trying to build a different bundle based on an argument passed to webpack.

I have a create-react-app that I have ejected from and currently currently if I do npm run build it builds a bundle using webpack. As I have both an english and spanish version of the site I was hoping that I could pass an argument here. i.e. to build a Spanish version something like npm run build:es.

My webpack file currently just builds the English bundle. There is a separate process during the application to pull in translations, but during the building of the bundle it would be great if I could stipulate which language to build the bundle for.

Anyone have any ideas.

The relevant webpack code is below:

//default messages for translations
var defaultMessages = require('/translations/en.json');

//more webpack stuff......

{
    test: /\.(js|jsx)$/,
    loader: require.resolve('string-replace-loader'),
    query: {
          multiple: Object.keys(defaultMessages).map(key => ({
           search: `__${key}__`,
           replace: defaultMessages[key]
          }))
    }
},

Upvotes: 4

Views: 3722

Answers (1)

Stefan Dragnev
Stefan Dragnev

Reputation: 14473

Webpack can receive a --env argument, which is then passed to the webpack.config file. The key is to export a function returning the configuration from your webpack.config.js, not the raw configuration.

$ webpack --env=lang_es

And in webpack.config.js:

module.exports = function(env) {
  if (env === 'lang_es') {
    // ...
  }
  return {
    module: {
      // ...
    },
    entry: {
      // ...
    }
  }
}

And in package.json:

"scripts": {
  "build_es": "webpack --env=lang_es",
}

This was originally really meant to distinguish between build types, e.g. development or production, but it's just a string passed into the config file - you can give it any meaning you want.

As hinted in the comments, using environment variables is the second, webpack-independent, approach. You can set the environment variable directly in package.json's scripts section:

"scripts": {
  "build_es": "BUILD_LANG=es webpack",
}

(Use cross-env to set the environment when developing on Windows).

And in webpack.config.js:

if (process.env.BUILD_LANG === 'es') {
  // ...
}

This environment-based approach has been used in a few places already (for example Babel's BABEL_ENV variable), so I'd say that it has gathered enough mileage to consider it proven and tested.

Edit: fixed the cross-env part to mention that it's only necessary on Windows.

Upvotes: 5

Related Questions