Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order dependencies: jQuery is not defined with browserify

I am trying to use a plugin that is in /js/lib/stellar.jquery.js:

var $ = require('jquery');

require('./lib/stellar.jquery')

$(function(){
    $.stellar();
});

When I run this though I get jQuery is not defined. I think the stellar jQuery plugin is loading before the jq library. At the bottom of the stellar plugin there's this code:

    ...
    // Expose the plugin class so it can be modified
    window.Stellar = Plugin;
}(jQuery, this, document));

Changing "jQuery" to "$" does not work either, gives "$ is not defined"

like image 407
Connor Leech Avatar asked Aug 15 '14 22:08

Connor Leech


2 Answers

Seems like another solution is to add :

global.jQuery = require("jquery")
like image 78
N3da Avatar answered Oct 14 '22 20:10

N3da


There is not any need to specify order for dependencies.

Because neither jQuery nor your plugin support CommonJS modules, you need to shim them to make them compatible with the browserify modules concept.

npm install browserify-shim --save-dev

add alias for jQuery and your plugin to your package.json (optional, but recommended)

"browser":{
  "customPlugin": "path/to/custom/plugin",
  "jquery": "./node_modules/jquery/dist/jquery.js"
}

add browserify shim transformation to enable shimming by adding to your package.json

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

configure shims

"browserify-shim": {
  "jquery"    :  "jQuery",
  "customPlugin" :  { "depends": [ "jquery:jQuery" ] },
}

Consider, in dependencies configuration before colon you should specify file name, NOT SHIMMED MODULE NAME!!! after colon you should specify identifier, which is expected by your module in global namespace.

Then, require your plugin to initialize it's code before usage

'use strict';

require('customPlugin');
var $ = require('jQuery');

$('.some-class-selector').myCustomPlugin();
like image 41
Andrew Kovalenko Avatar answered Oct 14 '22 18:10

Andrew Kovalenko