order dependencies: jQuery is not defined with browserify

随声附和 提交于 2019-11-29 13:33:32

问题


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")


来源:https://stackoverflow.com/questions/25334974/order-dependencies-jquery-is-not-defined-with-browserify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!