javascript - Browserify 动态分离包

标签 javascript browserify commonjs

我的应用程序将给定语言的消息对象加载到应用程序中。我的结构是这样的:

/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 构建主应用程序并为所有语言文件单独打包,并且仍然允许 MyApprequire那些语言文件?

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 to require 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 in lang/. So you can still include your favored language.

编辑:在捆绑 MyApp.js 时使用 --ignore-missing--im。所以您可以要求所有语言,当它们丢失时它们仍然是未定义

关于javascript - Browserify 动态分离包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30751543/

相关文章:

javascript - 使用 babel.js 而不是 browserify 编译成 bundle

javascript - 无法在 Vue.js 中重用模板

javascript - Gulp + Browserify 任务不起作用(无输出)

javascript - 为什么在 JavaScript 中导入模块有不同的方法?

javascript - 选择器仅在 setTimeout 中找到合适的值

JavaScript ES6 : unable to change value of button with ajax (with the rest of the js code working fine)

javascript - React Native Android 中 View 之间的导航示例?

javascript - 如何使用 JQuery 根据 HTML 多选下拉列表定义的多个搜索条件搜索 XML 中的数据

javascript - 我如何将 ts 代码编译为 'require([' somemodule'])

javascript - node.js 用漂亮的名字定义自己的模块