简体   繁体   中英

How to avoid code duplication using Browserify

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:

Lets say, I have page1.js and page2.js make use of jquery.js and 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.

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">

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

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 tags:

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

you could also create a seperate bundle for jquery and jquery-ui with this command line:

browserify -r jquery -r jquery-ui > modules.js

add <script src="modules.js"></script> to html and add -x jquery -x jquery-ui to your two bundles.

browserify -x jquery -x jquery-ui page1.js > bundle1.js
browserify -x jquery -x jquery-ui page2.js > bundle2.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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