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;
You can separate all languages from your main app by using
-r
(require) and-x
(external) in yourbrowserify
command.Bundle languages together to one file, could look like this:
Then include the new file (
languages.js
) in your html page beforeMyApp.js
. Then you have to ignore them while buildingMyApp.js
.You are still allowed to
require
those languages.There is no browserify-way to do that automatically for each file in
lang/
.EDIT: use
--ignore-missing
or--im
when bundleingMyApp.js
. So you canrequire
all languages and when they are missing they are stillundefined
.