我的应用程序将给定语言的消息对象加载到应用程序中。我的结构是这样的:
/lang
/en.js (100 kb file)
/ru.js (100 kb file)
/... many more
app.js (this is `MyApp` as below)
语言文件非常大,所以我想创建单独的包,然后你只包含你需要的文件 <script src="lang/en.js"></script>
.语言也可以随时在应用程序中“切换”。
我如何告诉 browserify 构建主应用程序并为所有语言文件单独打包,并且仍然允许 MyApp
至 require
那些语言文件?
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;
最佳答案
您可以通过在 browserify
命令中使用 -r
(要求)和 -x
(外部)将所有语言从您的主应用程序中分离出来.
将语言捆绑到一个文件中,可能如下所示:
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.
然后在 MyApp.js
之前将新文件 (languages.js
) 包含在您的 html 页面中。然后你必须在构建 MyApp.js
时忽略它们。
browserify --ignore-missing -x ./lang/en.js -x ./lang/ru.js -d app.js > MyApp.js
您仍然可以要求
那些语言。
NOTE: If you have a separate bundle for each language (see
RECOMMENDED
), you are only allowed torequire
the included ones in your main app.
lang/
中的每个文件都没有 browserify-way 自动执行此操作。
I recommend you to write a
*.cmd
(batch) file that executes the above commands for every language file inlang/
. So you can still include your favored language.
编辑:在捆绑 MyApp.js
时使用 --ignore-missing
或 --im
。所以您可以要求
所有语言,当它们丢失时它们仍然是未定义
。
关于javascript - Browserify 动态分离包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30751543/