How to avoid code duplication using Browserify

佐手、 提交于 2019-12-10 19:26:58

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/30294003/how-to-avoid-code-duplication-using-browserify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!