How can I use npm for front-end dependencies?

dev.pus picture dev.pus · Jul 7, 2012 · Viewed 18k times · Source

I want to ask if it is possible (and generally a good idea) to use npm to handle front-end dependencies (Backbone, jQuery).

I have found that Backbone, jQuery and so on are all available through npm but I would have to set another extraction point (the default is node_modules) or symlink or something else...

Has somebody done this before?

Is it possible?

What do I have to change in package.json?

Answer

Derek Reynolds picture Derek Reynolds · Jul 2, 2014

+1 for using Browserify. We use it here at diy.org and love it. The best introduction and reasoning behind Browserify can be found in the Browserify Handbook. Topics like CommonJS & AMD solutions, build pipelines and testing are covered there.

The main reason Browserify works so well is it transparently works w/ NPM. As long as a module can be required it can be Browserified (though not all modules are made to work in the browser).

Basics:

npm install jquery-browserify

main.js

var $ = require('jquery-browserify');
$("img[attr$='png']").hide();

Then run:

browserify main.js > bundle.js

Then include bundle.js in your HTML doc and the code in main.js will execute.