How do I use Browserify with external dependencies?

前端 未结 3 1188
清歌不尽
清歌不尽 2020-11-30 23:49

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

3条回答
  •  长情又很酷
    2020-12-01 00:08

    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).

提交回复
热议问题