Require.JS shim配置全局范围?

时间:2013-04-02 13:25:56

标签: requirejs shim

我有针对requireJS的以下设置。

requirejs.config({
     paths: {
            'resources' : '/Scripts/resources'
     },
     shim: {
             'resources': {
                           exports: 'LocalizedStrings'
           }
     }
});

我的资源.JS如下:

LocalizedStrings = {
                    title: "Demo",
                    save: "Save"
}

现在当我在main.JS文件中加载资源作为依赖项时,我可以访问LocalizedStrings并且它可以工作。

//main.js
define(function(require){
    var LocalizedStrings = require('resources');
    console.log(LocalizedStrings); //works as expected
});

但是在其他模块上,我并不需要将资源作为依赖项加载来访问“LocalizedStrings”。

//othermodule.js
define(function(require){
    console.log(LocalizedStrings); //works as expected even though resources dependency is not loaded
});

我在这里不明白的是,如果我使用shim加载一个JS文件并加载一次,它是否全局可用,我不必再在其他模块中加载相同的依赖项。

1 个答案:

答案 0 :(得分:18)

Backbone和Underscore都修改了全局范围,因此如果浏览器运行了他们的代码,那么全局变量就会存在。

如果在RequireJS中加载为填充程序,或者就像直接在其src中包含脚本标记一样,就会发生这种情况。

一旦存在全局变量,它们就存在(除非明确delete我猜)。

This jsfiddle is a simple example of using shims,并看到值(对于某些库)被设置为全局。

该示例的目的是显示全局变量的值仅在require()调用内保证。(如果使用AMD加载程序,而不是简单地导入库中)一个script标签)。并且全局变量的值将在未来某个不确定的时间存在。

源代码

require.config({
    shim: {
        underscore: {
            exports: '_'
        },
        backbone: {
            deps: ["underscore", "jquery"],
            exports: "Backbone"
        }
    },
    paths: {
        jquery: "http://code.jquery.com/jquery-1.9.1",
        backbone: "http://backbonejs.org/backbone",
        underscore: "http://underscorejs.org/underscore"
    }
});

function appendVersions(msg, $, _, Backbone) {
    var pre = document.getElementById("content");
    var s = "<h2>" + msg + "</h2>";
    s += "jquery=";
    try { s += $.fn.jquery; } catch (e) { s += e.msg; }
    s += "<br>";
    s += "_=";
    try { s += _.VERSION; } catch (e) {  s += e.msg; }
    s += "<br>";
    s += "Backbone=";
    try { s += Backbone.VERSION; } catch (e) {  s += e.msg; }
    pre.innerHTML += s;
}

appendVersions("Before require (will be undefined)", window["$"], window["_"], window["Backbone"]);

require(["jquery", "underscore", "backbone"], function ($, _, Backbone) {
    appendVersions("Inside Require (should *always* be ok, unless the scripts aren't there)", $, _, Backbone);
});

appendVersions("After require (Probably be undefined, as the require probably won't have loaded the scripts yet)", window["$"], window["_"], window["Backbone"]);

setTimeout(function () {
    appendVersions("After Timeout (should be ok, but depends on how quickly the scripts load. Try changing the timeout duration)", window["$"], window["_"], window["Backbone"]);
}, 2000);

示例输出

enter image description here