如何使用Browserify避免代码重复 [英] How to avoid code duplication using Browserify

查看:132
本文介绍了如何使用Browserify避免代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CommonJS菜鸟,在这里,我读到有关browserify的内容,并认为它比现有的RequireJS设置要简单,所以我继续进行更改。我发现我将在每个捆绑软件中都有代码重复。让我解释一下:

CommonJS noob here, I read about browserify and thought it was simpler than my existing RequireJS setup, so I went ahead and changed them. What I have found out is I am going to have code duplication in each bundle. Let me explain:

让我说,我有 page1.js page2.js 使用 jquery.js jquery-ui.js

Lets say, I have page1.js and page2.js make use of jquery.js and jquery-ui.js

现在我必须创建 bundle1.js bundle2.js 并每个包中都重复了 jquery.js jquery-ui.js 的内容。

Now I have to create bundle1.js and bundle2.js and the content of jquery.js and jquery-ui.js is duplicated in each bundle.

我尝试通过仅捆绑 jquery.js jquery-ui.js ,例如:

I have tried separated into different files in browser by only bundling the jquery.js and jquery-ui.js such as:

<script src="lib_bundle.js">
<script src="page1.js">

问题是需要 c $ c> page1.js 将失败,因为它不是commonjs包。

Problem is that the require within page1.js will fail because it's not a commonjs bundle.

推荐答案

外部需求的目的是什么。我不熟悉browserify的命令行,但是在使用JavaScript API时,您可以执行以下操作。这会将常见的依赖项捆绑在一起。

This situation is what external requires are for. I'm not familiar with the command line for browserify, but when using the JavaScript API, you can do the following. This will bundle common dependencies together. They can then be referenced as "externals" by your other bundles.

var browserify = require('browserify');

var externalDependencies = [
  'jquery',
  'jquery-ui'
];

// shared libraries bundle (i.e. jquery, jquery-ui)
var libsBundle = browserify({
  // your options
  // ...
  require: externalDependencies
});

// main bundle (i.e. page1, page2)
var mainBundle = browserify({
  // your options
  // ...
});
mainBundle.external(externalDependencies);

libsBundle.bundle();
mainBundle.bundle();

脚本标签:

<script src="libsBundle.js">
<script src="mainBundle.js">

这篇关于如何使用Browserify避免代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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