【问题标题】:order dependencies: jQuery is not defined with browserify顺序依赖:jQuery 没有用 browserify 定义
【发布时间】:2014-10-09 16:39:35
【问题描述】:

我正在尝试使用/js/lib/stellar.jquery.js 中的插件:

var $ = require('jquery');

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

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

当我运行它时,虽然我没有定义 jQuery。我认为恒星 jQuery 插件在 jq 库之前加载。在stellar 插件的底部有这段代码:

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

将“jQuery”更改为“$”也不起作用,给出“$ is not defined”

【问题讨论】:

  • 插件是否兼容CommonJS?如果不是,那一定是问题所在。
  • 所以我必须browserify-shim这个插件吗?不知道该怎么做

标签: javascript jquery npm browserify


【解决方案1】:

不需要指定依赖的顺序。

因为 jQuery 和您的插件都不支持 CommonJS 模块,所以您需要填充它们以使它们与 browserify 模块概念兼容。

npm install browserify-shim --save-dev

jQuery您的插件 的别名添加到您的 package.json(可选,但推荐)

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

添加 browserify shim 转换以通过添加到您的 package.json 来启用 shiming

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

配置垫片

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

考虑一下,在冒号前的依赖项配置中,您应该指定 文件名,而不是 SHIMMED MODULE NAME!!! 在冒号之后你应该指定标识符,这是你的模块在全局命名空间中所期望的。

然后,要求你的插件在使用前初始化它的代码

'use strict';

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

$('.some-class-selector').myCustomPlugin();

【讨论】:

    【解决方案2】:

    好像another solution 是添加:

    global.jQuery = require("jquery")
    

    【讨论】:

    • 或 window.$ = require('jquery');
    • 我认为这是更好的 window.$ = window.jQuery = require('jquery');
    • 对不起,如果这是一个愚蠢的问题,但你会在哪里添加那行?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2017-02-28
    相关资源
    最近更新 更多