Browse dynamic individual packages
My application loads a message object in a given language into my application. My structure looks like this:
/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 large, so I would like to create separate packages, and then you only include the files you need <script src="lang/en.js"></script>
. The language can also be "turned on" in the app at any time.
How can I tell the browser to create the core application and the individual packages for all language files and still allow MyApp
to require
these 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;
source to share
You can decouple all languages โโfrom the main application using -r
(require) and -x
(external) in your command browserify
.
Linking languages โโtogether with one file might look like this:
browserify -r ./lang/en.js -r ./lang/ru.js > languages.js
RECOMMENDED: You can create a separate package for each language file using the above command. Just use it
-r
once.
Then add a new file ( languages.js
) to the html page before MyApp.js
. Then you must ignore them when building MyApp.js
.
browserify --ignore-missing -x ./lang/en.js -x ./lang/ru.js -d app.js > MyApp.js
You can still use require
these languages.
NOTE. If you have a separate package for each language (see
RECOMMENDED
), you are allowed to userequire
those included in the main application.
For every file in lang/
there, there is no way for the browser to do this automatically.
I recommend that you write a file
*.cmd
(batch) that runs the above commands for each language file inlang/
. This way, you can still specify your preferred language.
EDIT: use --ignore-missing
or --im
when typing MyApp.js
. This way you can require
all languages โโand when they are missing they are still undefined
.
source to share