Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 268
James Lin Avatar asked Dec 20 '25 14:12

James Lin


1 Answers

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">
like image 116
user2943490 Avatar answered Dec 22 '25 03:12

user2943490



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!