Avoiding Code Duplication Using Browserify

CommonJS noob here, I read about browning and thought it was easier than my existing RequireJS installation, so I went ahead and changed them. I found that I will have code duplication in each set. Let me explain:

Suppose I have page1.js and page2.js use jquery.js and jquery-ui.js

Now I need to create bundle1.js and bundle2.js , and the contents of jquery.js and jquery-ui.js will be duplicated in each set.

I tried to split into different files in the browser, only by linking jquery.js and jquery-ui.js , for example:

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

The problem is that require inside page1.js will not work because it is not a generic package.

+3
source share
2 answers

This situation is external requirements . I am not familiar with the command line for the browser, but using the JavaScript API you can do the following. This will combine common dependencies. Then they can be called "external" your other bundles.

 var browserify = require('browserify'); var externalDependencies = [ 'jquery', 'jquery-ui' ]; // shared libraries bundle (ie jquery, jquery-ui) var libsBundle = browserify({ // your options // ... require: externalDependencies }); // main bundle (ie page1, page2) var mainBundle = browserify({ // your options // ... }); mainBundle.external(externalDependencies); libsBundle.bundle(); mainBundle.bundle(); 

Script tags:

 <script src="libsBundle.js"> <script src="mainBundle.js"> 
+3
source

you can also create a separate kit for jquery and jquery-ui using 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 packages.

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

All Articles