Browserify dynamic separate bundles

173 views Asked by At

My app loads an object of messages in a given language into the application. My structure is like so:

/lang
    /en.js (100 kb file)
    /ru.js (100 kb file)
    /... many more
app.js (this is `MyApp` as below)

The language files are very big so I would like to create separate bundles and you then only include the files you need <script src="lang/en.js"></script>. The language can also be 'switched' within the application at any time.

How would I tell browserify to build the main app and separate bundles for all the language files, and still allow MyApp to require those language files?

function MyApp(lang) {
    this.messages = {};
    this.switchLang(lang);
};

MyApp.prototype.loadLang = function(lang) {
    this.messages = require('./lang/' + lang + '.js');
};

MyApp.prototype.switchLang = function(lang) {
    this.lang = lang;
    this.loadLang(lang);
};

MyApp.prototype.sayHello = function() {
    alert(this.messages.HELLO);
};

module.exports = MyApp;
1

There are 1 answers

2
marcel On BEST ANSWER

You can separate all languages from your main app by using -r (require) and -x (external) in your browserify command.

Bundle languages together to one file, could look like this:

browserify -r ./lang/en.js -r ./lang/ru.js > languages.js

RECOMMENDED: You can create a separate bundle for each language file with the above command. Just use -r once.

Then include the new file (languages.js) in your html page before MyApp.js. Then you have to ignore them while building MyApp.js.

browserify --ignore-missing -x ./lang/en.js -x ./lang/ru.js -d app.js > MyApp.js

You are still allowed to require those languages.

NOTE: If you have a separate bundle for each language (see RECOMMENDED), you are only allowed to require the included ones in your main app.

There is no browserify-way to do that automatically for each file in lang/.

I recommend you to write a *.cmd (batch) file that executes the above commands for every language file in lang/. So you can still include your favored language.

EDIT: use --ignore-missing or --im when bundleing MyApp.js. So you can require all languages and when they are missing they are still undefined.