Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jquery with browserify

I am trying to use jQuery with browserify with the module jquery-browserify. I required the module in my client.js script as such:

    var $ = require('jquery-browserify');

and when I run my node server, after i've ran browserify, i get a "window is not defined" error. What am I doing wrong?

like image 994
Misbah Khan Avatar asked Jul 08 '12 00:07

Misbah Khan


People also ask

When should I use Browserify?

Browserify solves the problems of having too many JS files referenced in your HTML, inability to use Node modules in the browser, and inability to reference your own modules in your own code. Watchify streamlines the process of bundling your files and will make a change every time you change a JS file in your project.

What is Browserify NPM?

require('modules') in the browser. Use a node-style require() to organize your browser code and load modules installed by npm. browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single <script> tag.

What is Browserify in Nodejs?

Browserify is an open-source JavaScript bundler tool that allows developers to write and use Node. js-style modules that compile for use in the browser.


3 Answers

jQuery is now CommonJS compliant, as of version 2.1.0

like image 179
Chris Avatar answered Oct 02 '22 12:10

Chris


Browserify can process CommonJS modules as well as AMD modules with the deamdify transform so now there should be no need to use a shim.

To be clear I only noticed AMD support in JQuery 2.0.0

like image 26
Andrew Hacking Avatar answered Oct 02 '22 14:10

Andrew Hacking


jQuery was not CommonJS compliant, i.e. it didn't export itself via module.exports = $ until 2.1.0.

Therefore you needed to shim it via browserify-shim.

browserify-shim will shim any version of jquery or any other non-CommonJS library like Zepto on the fly. Details on how to set this up are included in the readme.

As an alternative you could have also used jquery-browserify, but then you would be tied to the jQuery version that this module made CommonJS compliant.

like image 45
Thorsten Lorenz Avatar answered Oct 02 '22 12:10

Thorsten Lorenz