Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack: Is it possible to evaluate javascript expression at compile time?

I'm trying to setup webpack for my project. The project is big enough and is provided in multiple languages. I want each of my entry points to be provided in each language as separate files. My language files are not just plain JSON, but JavaScript instead. So i18n plugin doesn't match my needs.

The solution seems to be similar to i18n plugin:

var languages = ['en', 'fr', 'de'];
module.exports = languages.map(function (lang) {
  return {
    name: lang,
    // some other language-dependent config
  }
})

Then in some of my scripts I want to require localization file, using environment variable:

var lang = ...; // some environment variable, available only at compile time
var l10n = require('./lang/' + lang);

But by default webpack tries to store that expression between parentheses assuming to evaluate it later in browser.

So is there a way to tell webpack to evaluate that immediately?

Or maybe someone has a better solution to my problem?

like image 934
Girafa Avatar asked Mar 13 '15 16:03

Girafa


1 Answers

You should be able to use Webpack's DefinePlugin to set the language at compile time.

For instance, you could write your require as:

var l10n = require('./lang/' + APPLICATION_LANGUAGE);

and in your config, have

plugins: [
  new webpack.DefinePlugin({
    APPLICATION_LANGUAGE: JSON.stringify(lang)
  })
]

You can have your build script conditionally set 'lang' based on some parameter or env variable or something.

like image 68
loganfsmyth Avatar answered Oct 15 '22 00:10

loganfsmyth