使用Browserify在页面之间共享公共代码 [英] Sharing common code across pages with Browserify

查看:88
本文介绍了使用Browserify在页面之间共享公共代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当大的多页面javascript应用程序,它使用requirejs来组织代码。我正在研究转向浏览器,因为我喜欢它提供的简单性,我已经习惯了node.js模块系统。

I have a fairly large multi-page javascript applications that uses requirejs to organize code. I am researching moving to browserify because I like the simplicity that it offers and I am already used to the node.js module system.

目前在每个页面上我都有javascript像这样

Currently on each page I have javascript that goes like this

<script data-main="/scripts/config/common" src="/scripts/lib/require.js">
<script data-main="/scripts/config/page-specific-js" src="/scripts/lib/require.js">

我有一个共同的构建步骤和每个页面的构建。这样就可以为每个页面缓存大部分JS。

and I have a common build step and a build for each page. This way the majority of the JS is cached for every page.

是否可以使用browserify执行类似操作?这样的缓存是否值得,或者将所有页面中的所有内容捆绑到一个文件中更好(考虑到可能只有一个页面可能依赖于大型外部库)?

Is it possible to do something similar with browserify? Is caching like this even worth it, or is it better to bundle everything into one file across all pages (considering that maybe only one page can depend on a large external library)?

推荐答案

您可以使用 factor-bundle 来完成此操作。您只需将代码拆分为每个文件的不同入口点。

You can use factor-bundle to do exactly this. You will just need to split your code up into different entry points for each file.

假设您有3页, / a / b / c 。每个页面对应一个入口点文件 /browser/a.js /browser.b.js ,以及 /browser/c.js 。使用因子包,你可以这样做:

Suppose you have 3 pages, /a, /b, and /c. Each page corresponds to an entry point file of /browser/a.js, /browser.b.js, and /browser/c.js. With factor-bundle, you can do:

browserify -p [ factor-bundle -o bundle/a.js -o bundle/b.js -o bundle/c.js ] \
  browser/a.js browser/b.js browser/c.js > bundle/common.js

超过1个入口点使用的任何文件都将被纳入bundle / common.js,而所有特定于页面的代码都将位于特定于页面的包文件中。现在,在每个页面上,您可以为公共包添加脚本标记,为特定于页面的包添加脚本标记。例如,对于/ a,您可以放置​​:

any files used by more than 1 of the entry points will be factored out into bundle/common.js, while all the page-specific code will be located in the page-specific bundle file. Now on each page you can put a script tag for the common bundle and a script tag for the page-specific bundle. For example, for /a you can put:

<script src="bundle/common.js"></script>
<script src="bundle/a.js"></script>

如果您不想使用命令行版本,您还可以使用factor-bundle 来自API

If you don't want to use the command-line version, you can also use factor-bundle from the API:

var browserify = require('browserify');
var fs = require('fs');

var files = [ './files/a.js', './files/b.js', './files/c.js' ];
var b = browserify(files);
b.plugin('factor-bundle', {
    outputs: [ 'bundle/a.js', 'bundle/b.js', 'bundle/c.js' ]
});
b.bundle().pipe(fs.createWriteStream('bundle/common.js'));

这篇关于使用Browserify在页面之间共享公共代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆