order dependencies: jQuery is not defined with browserify

前端 未结 2 982
一生所求
一生所求 2020-12-31 13:19

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

var $ = require(\'jquery\');

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

$(function(){         


        
2条回答
  •  有刺的猬
    2020-12-31 13:58

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

提交回复
热议问题