3

在我的项目中,我想使用 RequireJS 并引导我的应用程序,如下所示:

requirejs.config({
baseUrl: 'scripts/vendor',
paths: {
    jquery: [
        'https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min',
        'jquery'
    ],
    angular: [
        'http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min',
        'angular'
    ],
    app: '../app'
}
});

require(['require', 'jquery', 'angular', 'app'], function(require, $, angular, app) {
console.log(require);
console.log($);
console.log(angular);
console.log(app);
});

在我的 index.html 上,只有 RequireJS 是通过 script 标签加载的,其中 RequireJS 加载了上面的代码。什么有效: - 在我的网络监视器中,我可以看到 RequireJS、jQuery、Angular 和应用程序已加载 - 对于 require、jQuery 和应用程序,console.log 消息打印正确

角度对象不知何故未定义。但是,如果我不从 CDN 加载它并使用我的本地加载,它就可以工作!本地文件是一个 RequireJS 包装器,如下所示:

define(['/components/angular/angular.min.js'], function () {
    return angular;
});

如何使用 Angular 的 CDN 完成这项工作?还是这取决于 Angular 的支持?

4

1 回答 1

2

首先,您将“路径”与“垫片”混淆了

路径很好,不要追求“垫片”行为。但是,您需要使您的“路径”正确:

paths: {
    jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min',
    // NOTE: angular is "plain JS" file
    angular: 'http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min',
    app: '../app'
}

然后,您需要放弃将某些东西归还给您的需求……只需“使用力量,卢克” :) 并期望在您需要时会出现正确的全局变量:

require(['jquery', 'app', 'angular'], function($, app, thisValueDoesNotMatter) {
    // you don't need to wrap "require" Just use global
    console.log(require);
    console.log($);
    console.log(app);

    // note, angular is loaded as "plain JavaScript" - not an AMD module.
    // it's ok. It returns "undefined" but we just don't care about its return value
    // just use global version of angular, which will be loaded by this time.
    // because you mentioned it in your dependencies list.
    console.log(window.angular);
});
于 2013-02-05T19:31:24.903 回答