prabir
prabir

Reputation: 7794

require cdn libraries in browserify without bundling it in the final js file

If I have a library that is being pulled down from cdn and wouldn't like it to be part of the final js file but be able to require it using browserify, how would I solve it?

Here is how I currently solve it using alias and a shim file.

browserify: {
    options: {
        debug: true,
        transform: [ 'reactify' ],
        alias: [
            'client/shims/jquery.js:jquery'
        ]
    },
    app: {
        src:  'client/app.js',
        dest: 'public/app.js'
    }
}

here is the shim file client/shims/jquery.js which I alias to jquery so I can use require('jquery') instead of the full path.

module.exports = $;

Is there a shortcut in grunt-browserify to support this scenario? I would like to know if it is possible to define it in Gruntfile.js without creating the shim file.

Adding external: [ 'jquery' ] seems to totally ignore it and doesn't work.

Upvotes: 37

Views: 9308

Answers (2)

kpimov
kpimov

Reputation: 13932

If you load jQuery before the Browserify bundle on the page, $ will be available as a global.

Upvotes: 0

silkAdmin
silkAdmin

Reputation: 4830

With browserify-shim you can add this in your package.json file:

  "browserify": {
    "transform": [
      "browserify-shim"
    ]
  },

  "browserify-shim": {
    "jquery": "global:$"
  }

Then jquery will be available in your modules via require('jquery')

Upvotes: 27

Related Questions