1

我在 index.html 文件的顶部和 main.js 中包含了modernizr / pollyfiller:

require.config({
    paths : {
    'jquery' : 'lib/jquery-1.10.2.min',
    'jqdate' : 'lib/jquery.dateFormat-1.0',
    'webshims' : 'lib/polyfiller'
},
shim : {
    'lib/underscore' : {
        exports : '_'
    },
    'lib/backbone' : {
        deps : ["lib/underscore", "jquery"],
        exports : 'Backbone'
    },
    "modernizr" : {
        deps : ["jquery"],
        exports : "modernizr"
    },
    "webshims" : {
        deps : [ "jquery", "lib/modernizr-custom"],
        exports: "webshims"
    }
}
});
var router, vent;

    require(["jquery", "lib/underscore", "lib/backbone", "app", "lib/modernizr-custom", "webshims"], function($, _, Backbone, Router, modernizr, webshims) {

$(function() {
    $.webshims.setOptions('forms forms-ext', {
        replaceUI : false,
        waitReady : false
    });

    $.webshims.polyfill('forms forms-ext');

    router = new Router();
    vent = _.extend({}, Backbone.Events);
    $.expr.cacheLength = 1;

    Backbone.history.start({

    });
});
});

这通常会加载正常,但是,有时看起来 webshims 在我尝试调用时没有定义:

    $.webshims.setOptions('forms forms-ext', {
        replaceUI : false,
        waitReady : false
    });

    $.webshims.polyfill('forms forms-ext');

我得到错误: TypeError: $.webshims is undefined

有没有更好的方法来加载这个?

编辑 所以,我像你说的那样更新了脚本,并且不得不在路径和 shim 定义中大写 Webshims。它加载正常,但现在我收到一个错误:

Uncaught SyntaxError: Unexpected token <

在 Chrome 和

SyntaxError: syntax error


<!DOCTYPE html>

在火狐中

4

1 回答 1

3

更新的答案

Alexander Farkas 在评论中指出,polyfiller 将自己定义为"polyfiller"

define('polyfiller', ['jquery'], factory);

所以:

  1. 加载 polyfiller.js 不需要 shim。

  2. 由 定义的模块polyfiller.js始终称为"polyfiller". 所以必须有一个paths将模块名称映射polyfiller到文件实际路径的设置polyfiller.js

因此,应修改原始配置以删除"webshims"shim,然后paths设置"webshims": "lib/polyfiller"应变为"polyfiller": "lib/polyfiller"并且 require 调用应为:

require(["jquery", "lib/underscore", "lib/backbone", "app", "lib/modernizr-custom", "polyfiller"], function($, _, Backbone, Router, modernizr) {

我已经从函数的参数中删除了最后一个变量,因为不需要传递模块值,因为polyfiller.js文件将自身注册为$.webshims.

这类似于 jQuery 定义自己的方式"jquery"(它不需要 shim 并且总是被调用"jquery")。

原始答案

更改您的require电话,以便您需要"webshims"而不是"lib/polyfiller"

require(["jquery", "lib/underscore", "lib/backbone", "app", "lib/modernizr-custom", "webshims"], ...

您问题中的代码显示您已设置paths配置选项,以便模块名称"webshims"解析为"lib/polyfiller",并为它创建了看起来合理的填充程序。但是,当您需要该webshims模块时,您将其称为"lib/polyfiller". RequireJS 不做反向解析来确定"lib/polyfiller""webshims".

或者,您可以删除"webshims"名称paths并重命名 shim,使其设置为"lib/polyfiller". 但是,我认为在整个应用程序中通过单字名称引用 3rd 方库而不是为它们提供路径是一种更好的做法。所以“jquery”、“bootstrap”、“underscore”和“webshims”等,而不是“lib/...”。

于 2013-11-19T16:06:08.507 回答