要求使用shim配置的原因和时间

时间:2022-05-09 20:52:03

i read the requirejs document from here api

我从这里api阅读requirejs文档

requirejs.config({
    shim: {
        'backbone': {
            //These script dependencies should be loaded before loading
            //backbone.js
            deps: ['underscore', 'jquery'],
            //Once loaded, use the global 'Backbone' as the
            //module value.
            exports: 'Backbone'
        },
        'underscore': {
            exports: '_'
        },
        'foo': {
            deps: ['bar'],
            exports: 'Foo',
            init: function (bar) {
                //Using a function allows you to call noConflict for
                //libraries that support it, and do other cleanup.
                //However, plugins for those libraries may still want
                //a global. "this" for the function will be the global
                //object. The dependencies will be passed in as
                //function arguments. If this function returns a value,
                //then that value is used as the module export value
                //instead of the object found via the 'exports' string.
                return this.Foo.noConflict();
            }
        }
    }
});

but i am not getting shim part of it. why should i use shim and how should i configure, can i get some more clarification

但我没有得到它的一部分。为什么我应该使用垫片,我应该如何配置,我可以得到更多的澄清

please can any one explain with example why and when should we use shim. thanks.

请任何人解释一下为什么以及何时应该使用垫片。谢谢。

3 个解决方案

#1


106  

A primary use of shim is with libraries that don't support AMD, but you need to manage their dependencies. For example, in the Backbone and Underscore example above: you know that Backbone requires Underscore, so suppose you wrote your code like this:

垫片的主要用途是不支持AMD的库,但您需要管理它们的依赖关系。例如,在上面的Backbone和Underscore示例中:您知道Backbone需要Underscore,所以假设您编写了如下代码:

require(['underscore', 'backbone']
, function( Underscore, Backbone ) {

    // do something with Backbone

}

RequireJS will kick off asynchronous requests for both Underscore and Backbone, but you don't know which one will come back first so it's possible that Backbone would try to do something with Underscore before it's loaded.

RequireJS将启动Underscore和Backbone的异步请求,但你不知道哪一个会先返回,所以Backbone可能会在加载之前尝试使用Underscore。

NOTE: this underscore/backbone example was written before both those libraries supported AMD. But the principle holds true for any libraries today that don't support AMD.

注意:这个下划线/主干示例是在这两个库支持AMD之前编写的。但是这个原则适用于今天不支持AMD的任何图书馆。

The "init" hook lets you do other advanced things, e.g. if a library would normally export two different things into the global namespace but you want to redefine them under a single namespace. Or, maybe you want to do some monkey patching on a methods in the library that you're loading.

“init”钩子可以让你做其他高级的事情,例如如果一个库通常会将两个不同的东西导出到全局命名空间中,但是你想在一个命名空间下重新定义它们。或者,也许你想对你正在加载的库中的方法进行一些猴子修补。

More background:

更多背景:

  • Upgrading to RequireJS 2.0 gives some history on how the order plugin tried to solve this in the past.
  • 升级到RequireJS 2.0提供了有关订单插件过去如何解决此问题的一些历史记录。
  • See the "Loading Non-Modules" section of This article by Aaron Hardy for another good description.
  • 有关其他说明,请参阅Aaron Hardy撰写本文的“加载非模块”部分。

#2


59  

As per RequireJS API documentation, shim lets you

根据RequireJS API文档,shim可以让你

Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value.

为不使用define()声明依赖项并设置模块值的旧的传统“浏览器全局”脚本配置依赖项,导出和自定义初始化。

- Configuring dependencies

- 配置依赖项

Lets say you have 2 javascript modules(moduleA and moduleB) and one of them(moduleA) depends on the other(moduleB). Both of these are necessary for your own module so you specify the dependencies in require() or define()

假设您有2个javascript模块(moduleA和moduleB),其中一个(moduleA)依赖于另一个(moduleB)。这两个对于您自己的模块都是必需的,因此您可以在require()或define()中指定依赖项

require(['moduleA','moduleB'],function(A,B ) {
    ...
}

But since require itself follow AMD, you have no idea which one would be fetched early. This is where shim comes to rescue.

但是由于要求自己遵循AMD,你不知道哪个会提前获取。这是垫片来救援的地方。

require.config({
    shim:{
       moduleA:{
         deps:['moduleB']
        } 
    }

})

This would make sure moduleB is always fetched before moduleA is loaded.

这将确保在加载moduleA之前始终获取moduleB。

- Configuring exports

- 配置导出

Shim export tells RequireJS what member on the global object (the window, assuming you're in a browser, of course) is the actual module value. Lets say moduleA adds itself to the window as 'modA'(just like jQuery and underscore does as $ and _ respectively), then we make our exports value 'modA'.

Shim导出告诉RequireJS全局对象上的哪个成员(当然,假设你在浏览器中的窗口)是实际的模块值。让我们说moduleA将自己添加到窗口中作为'modA'(就像jQuery和下划线分别为$和_),然后我们将导出值设为'modA'。

require.config({
    shim:{
       moduleA:{
         exports:'modA'
        } 
    }

It will give RequireJS a local reference to this module. The global modA will still exist on the page too.

它将为RequireJS提供本模块的本地引用。全局modA也将存在于页面上。

-Custom initialization for older "browser global" scripts

- 旧的“浏览器全局”脚本的自定义初始化

This is probably the most important feature of shim config which allow us to add 'browser global', 'non-AMD' scripts(that do not follow modular pattern either) as dependencies in our own module.

这可能是shim config最重要的特性,它允许我们在我们自己的模块中添加“浏览器全局”,“非AMD”脚本(也不遵循模块化模式)作为依赖项。

Lets say moduleB is plain old javascript with just two functions funcA() and funcB().

让我们说moduleB是普通的旧javascript,只有两个函数funcA()和funcB()。

function funcA(){
    console.log("this is function A")
}
function funcB(){
    console.log("this is function B")
}

Though both of these functions are available in window scope, RequireJS recommends us to use them through their global identifier/handle to avoid confusions. So configuring the shim as

尽管这些功能都可以在窗口范围内使用,但RequireJS建议我们通过其全局标识符/句柄使用它们以避免混淆。所以将垫片配置为

shim: {
    moduleB: {
        deps: ["jquery"],
        exports: "funcB",
        init: function () {
            return {
                funcA: funcA,
                funcB: funcB
            };
        }
    }
}

The return value from init function is used as the module export value instead of the object found via the 'exports' string. This will allow us to use funcB in our own module as

init函数的返回值用作模块导出值,而不是通过'exports'字符串找到的对象。这将允许我们在我们自己的模块中使用funcB

require(["moduleA","moduleB"], function(A, B){
    B.funcB()
})

Hope this helped.

希望这有帮助。

#3


-3  

you must add paths in requirejs.config to declare, example :

你必须在requirejs.config中添加路径来声明,例如:

requirejs.config({
    paths: {
          'underscore' : '.../example/XX.js' /// your file java script
          'jquery' : '.../example/jquery.js' /// your file java script
    }
    shim: {
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        'underscore': {
            exports: '_'
        },
        'foo': {
            deps: ['bar'],
            exports: 'Foo',
            init: function (bar) {
                return this.Foo.noConflict();
            }
        }
    }
});

#1


106  

A primary use of shim is with libraries that don't support AMD, but you need to manage their dependencies. For example, in the Backbone and Underscore example above: you know that Backbone requires Underscore, so suppose you wrote your code like this:

垫片的主要用途是不支持AMD的库,但您需要管理它们的依赖关系。例如,在上面的Backbone和Underscore示例中:您知道Backbone需要Underscore,所以假设您编写了如下代码:

require(['underscore', 'backbone']
, function( Underscore, Backbone ) {

    // do something with Backbone

}

RequireJS will kick off asynchronous requests for both Underscore and Backbone, but you don't know which one will come back first so it's possible that Backbone would try to do something with Underscore before it's loaded.

RequireJS将启动Underscore和Backbone的异步请求,但你不知道哪一个会先返回,所以Backbone可能会在加载之前尝试使用Underscore。

NOTE: this underscore/backbone example was written before both those libraries supported AMD. But the principle holds true for any libraries today that don't support AMD.

注意:这个下划线/主干示例是在这两个库支持AMD之前编写的。但是这个原则适用于今天不支持AMD的任何图书馆。

The "init" hook lets you do other advanced things, e.g. if a library would normally export two different things into the global namespace but you want to redefine them under a single namespace. Or, maybe you want to do some monkey patching on a methods in the library that you're loading.

“init”钩子可以让你做其他高级的事情,例如如果一个库通常会将两个不同的东西导出到全局命名空间中,但是你想在一个命名空间下重新定义它们。或者,也许你想对你正在加载的库中的方法进行一些猴子修补。

More background:

更多背景:

  • Upgrading to RequireJS 2.0 gives some history on how the order plugin tried to solve this in the past.
  • 升级到RequireJS 2.0提供了有关订单插件过去如何解决此问题的一些历史记录。
  • See the "Loading Non-Modules" section of This article by Aaron Hardy for another good description.
  • 有关其他说明,请参阅Aaron Hardy撰写本文的“加载非模块”部分。

#2


59  

As per RequireJS API documentation, shim lets you

根据RequireJS API文档,shim可以让你

Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value.

为不使用define()声明依赖项并设置模块值的旧的传统“浏览器全局”脚本配置依赖项,导出和自定义初始化。

- Configuring dependencies

- 配置依赖项

Lets say you have 2 javascript modules(moduleA and moduleB) and one of them(moduleA) depends on the other(moduleB). Both of these are necessary for your own module so you specify the dependencies in require() or define()

假设您有2个javascript模块(moduleA和moduleB),其中一个(moduleA)依赖于另一个(moduleB)。这两个对于您自己的模块都是必需的,因此您可以在require()或define()中指定依赖项

require(['moduleA','moduleB'],function(A,B ) {
    ...
}

But since require itself follow AMD, you have no idea which one would be fetched early. This is where shim comes to rescue.

但是由于要求自己遵循AMD,你不知道哪个会提前获取。这是垫片来救援的地方。

require.config({
    shim:{
       moduleA:{
         deps:['moduleB']
        } 
    }

})

This would make sure moduleB is always fetched before moduleA is loaded.

这将确保在加载moduleA之前始终获取moduleB。

- Configuring exports

- 配置导出

Shim export tells RequireJS what member on the global object (the window, assuming you're in a browser, of course) is the actual module value. Lets say moduleA adds itself to the window as 'modA'(just like jQuery and underscore does as $ and _ respectively), then we make our exports value 'modA'.

Shim导出告诉RequireJS全局对象上的哪个成员(当然,假设你在浏览器中的窗口)是实际的模块值。让我们说moduleA将自己添加到窗口中作为'modA'(就像jQuery和下划线分别为$和_),然后我们将导出值设为'modA'。

require.config({
    shim:{
       moduleA:{
         exports:'modA'
        } 
    }

It will give RequireJS a local reference to this module. The global modA will still exist on the page too.

它将为RequireJS提供本模块的本地引用。全局modA也将存在于页面上。

-Custom initialization for older "browser global" scripts

- 旧的“浏览器全局”脚本的自定义初始化

This is probably the most important feature of shim config which allow us to add 'browser global', 'non-AMD' scripts(that do not follow modular pattern either) as dependencies in our own module.

这可能是shim config最重要的特性,它允许我们在我们自己的模块中添加“浏览器全局”,“非AMD”脚本(也不遵循模块化模式)作为依赖项。

Lets say moduleB is plain old javascript with just two functions funcA() and funcB().

让我们说moduleB是普通的旧javascript,只有两个函数funcA()和funcB()。

function funcA(){
    console.log("this is function A")
}
function funcB(){
    console.log("this is function B")
}

Though both of these functions are available in window scope, RequireJS recommends us to use them through their global identifier/handle to avoid confusions. So configuring the shim as

尽管这些功能都可以在窗口范围内使用,但RequireJS建议我们通过其全局标识符/句柄使用它们以避免混淆。所以将垫片配置为

shim: {
    moduleB: {
        deps: ["jquery"],
        exports: "funcB",
        init: function () {
            return {
                funcA: funcA,
                funcB: funcB
            };
        }
    }
}

The return value from init function is used as the module export value instead of the object found via the 'exports' string. This will allow us to use funcB in our own module as

init函数的返回值用作模块导出值,而不是通过'exports'字符串找到的对象。这将允许我们在我们自己的模块中使用funcB

require(["moduleA","moduleB"], function(A, B){
    B.funcB()
})

Hope this helped.

希望这有帮助。

#3


-3  

you must add paths in requirejs.config to declare, example :

你必须在requirejs.config中添加路径来声明,例如:

requirejs.config({
    paths: {
          'underscore' : '.../example/XX.js' /// your file java script
          'jquery' : '.../example/jquery.js' /// your file java script
    }
    shim: {
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        'underscore': {
            exports: '_'
        },
        'foo': {
            deps: ['bar'],
            exports: 'Foo',
            init: function (bar) {
                return this.Foo.noConflict();
            }
        }
    }
});