gpt4 book ai didi

javascript - Requirejs 为什么以及何时使用垫片配置

转载 作者:IT王子 更新时间:2023-10-29 02:43:16 24 4
gpt4 key购买 nike

我从这里阅读了requirejs文档API

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();
}
}
}
});

但我没有得到 shim 的一部分。为什么我应该使用 shim 以及我应该如何配置,我能得到更多的说明吗

请任何人举例说明为什么以及何时应该使用 shim。谢谢。

最佳答案

shim 的主要用途是用于不支持 AMD 的库,但您需要管理它们的依赖项。例如,在上面的 Backbone 和 Underscore 示例中:您知道 Backbone 需要 Underscore,所以假设您这样编写代码:

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

// do something with Backbone

}

RequireJS 将启动对 Underscore 和 Backbone 的异步请求,但您不知道哪个会先返回,因此 Backbone 可能会在加载之前尝试对 Underscore 执行某些操作。

注意:这个下划线/ Backbone 示例是在这两个库都支持 AMD 之前编写的。但该原则适用于当今任何不支持 AMD 的库。

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

更多背景:

关于javascript - Requirejs 为什么以及何时使用垫片配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15471088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com