I'm trying to migrate from RequireJS to Webpack and I'm not sure the best way to handle our locale files.
Currently, we generate a separate JS file for each locale. These files contain 7+ module definitions for i18n messages as well as library configurations (such as moment). For example, our da_DK file looks something like:
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define('moment-locale',['moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var da = moment.defineLocale('da', {
...
});
return da;
}));
define('messages',[],function(){
var da_messages = {
...
};
return da_messages;
});
At runtime, we determine the appropriate language file to load with the rest of our app. Our app code has no idea which locale is loaded; any modules that depend on the locale will do require('moment-locale')
and require('messages')
.
I'm wanting to do something similar with Webpack, but I haven't found a good way to accomplish this yet.
I've seen require.context
for dynamic requires, but it sounds like that would end up bundling all of the possible locales with my app, which I'd prefer not to do.
I also looked into the DllPlugin, thinking each locale file could be a "dll", but I noticed the dll manifest contains specific module names (ex: node_modules/moment/locale/de-at.js) and I think I'd need that to be more generic so webpack knows when I require('moment-locale')
, it needs to look in that dll.
One way I was able to get this to work was by updating my locale bundle generation code so that it creates an entry for each locale that looks like:
module.exports = {
'messages': require('messages'),
'moment-locale': require('moment-locale'),
...
};
and then in the webpack configuration, I set the library
field to a namespace for my app. And then in my app's webpack config, I referenced these modules in the externals
. So in other words, when da_DK.js is loaded, it places all the modules on the window
under a namespace for the app to reference when it loads. I'd rather not use this approach, but it's the only way I've been able to get this to work so far.
Is there another/better way to accomplish this?