Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

javascript - How do I use Browserify with external dependencies?

I am trying to slowly introduce Browserify into my site, but I don't want to rewrite all the js and I don't want duplicate instances of jquery and other libraries bundled with my Browserify build.

If I build my module listing jquery as an external dependency, how do I then point it at my global jquery instance? Also the goal is to eliminate the mylibs global (example below), so I don't want to use it in my module.

This is what I'm trying to do (psudo-code). This would be in my site's repo - not the module's. The module would be installed with Bower:

var mylibs.jQuery = $.noConflict(); // global used by lots of existing code
module.exports = {
    jquery: mylibs.jQuery // can be imported by my module as require('jquery')
};

Something like that is what I'm trying to achieve. Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can achieve that by using browserify-shim. Assuming that you've got a module named mymodule.js that depends on jQuery in the global scope with the following contents:

var $ = require('jQuery');

console.log(typeof $);
  1. Install browserify-shim:

    npm install browserify-shim --save-dev
    
  2. In package.json file, tell browserify to use browserify-shim as a transform:

    {
        "browserify": {
            "transform": [ "browserify-shim" ]
        }
    }
    
  3. In package.json file, tell browserify-shim to map jQuery to the jQuery in the global scope:

    {
        "browserify-shim": {
            "jQuery": "global:jQuery"
        }
    }
    
  4. Run browserify

    browserify mymodule.js > bundle.js
    

If you examine bundle.js you will notice that require('jQuery') is replaced with (window.jQuery).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...