简体   繁体   English

Browserify动态单独捆绑

[英]Browserify dynamic separate bundles

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> . 语言文件非常大,所以我想创建单独的包,然后只包含你需要的文件<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? 我如何告诉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;

You can separate all languages from your main app by using -r (require) and -x (external) in your browserify command. 您可以在browserify命令中使用-r (require)和-x (external)将所有语言与主应用程序分开。

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. 只需使用-r一次。

Then include the new file ( languages.js ) in your html page before MyApp.js . 然后 MyApp.js 之前的html页面中包含新文件( languages.js )。 Then you have to ignore them while building MyApp.js . 然后你必须在构建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. 您仍然可以require这些语言。

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. 注:如果您对每种语言(参见单独的包RECOMMENDED ),你只被允许require所包含的那些在主应用程序。

There is no browserify-way to do that automatically for each file in lang/ . 没有browserify方法为lang/每个文件自动执行此操作。

I recommend you to write a *.cmd (batch) file that executes the above commands for every language file in lang/ . 我建议你写一个*.cmd (批处理)文件,为lang/每个语言文件执行上述命令。 So you can still include your favored language. 所以你仍然可以包括你喜欢的语言。

EDIT: use --ignore-missing or --im when bundleing MyApp.js . 编辑: --im时使用--ignore-missingMyApp.js So you can require all languages and when they are missing they are still undefined . 因此,您可以require所有语言,当它们丢失时,它们仍然是undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM