order dependencies: jQuery is not defined with bro

2019-02-06 17:44发布

问题:

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"

回答1:

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();


回答2:

Seems like another solution is to add :

global.jQuery = require("jquery")