Search code examples
javascriptcommonjs

I want to use global jQuery at commonjs module


I developed application with commonjs modules. like

var $ = require('jquery');

This time, i want to change commonjs jQuery module to global include jQuery.

Solution: Change every require syntax.

var $ = require('jquery'); => var $ = window.jQuery;

But I think, this is not awesome.

Is there anything awesome way? (ex. Suppose...browserify options????)


Solution

  • Check out Webpack because Browserify is slowly dying out. Webpack works with CommonJS and npm, so all you have to do is point Webpack to your node_modules directory in the webpack.config.js (under the resolve.moduleDirectories key) to get what you want. It will automatically pull jquery from the node_modules directory and wrap it in a commonjs-like fashion for you, as part of the way Webpack functions.

    It can work by itself as its own build tool, or you can run it from gulp using gulp-webpack. I haven't checked but I am sure there'd be a grunt version as well, if that is what you use.

    The initial configuration will take you a little bit of time but it's definitely worth the effort and learning curve.

    Resources: