我可以编写一个 javascript 文件,在它可用时选择使用 require.js 来指定依赖项吗? [英] Can I write a javascript file that optionally uses require.js to specifies dependencies when it is available?
问题描述
我需要编写一个 javascript 插件,它既可以用作 AMD 模块,也可以用作非 AMD(同步加载)javascript 文件.
I need to write a javascript plugin that can be used both as an AMD module and as a non-AMD (synchronously loaded) javascript file.
它依赖于Jockey.js"和 jquery 库.
It has a dependency on the "Jockey.js" and jquery libraries.
换句话说,我想构建文件,使其在传统的非异步 html 结构中使用时不会失败(通过脚本标签加载,在通过脚本标签加载其依赖项之后),但是这样它也可以在没有垫片的情况下作为 AMD 模块工作,并指定其依赖项.这可以做到吗,还是只有 shim 才能做到这一点?
In other words, I'd like to structure the file so that it doesn't fail when its used in a traditional non-async html structure (loaded via a script tag, after its dependencies are loaded via script tags), but so that it will also be able to work as an AMD module without shim, and specify its dependencies. Can this be done, or is shim the only way to do this?
推荐答案
可以做到.我有一个这样的插件就在这里一>.这是一般结构:
It can be done. I've got one such plugin right here. Here's the general structure:
(function (factory) {
// If in an AMD environment, define() our module, else use the
// jQuery global.
'use strict';
if (typeof define === 'function' && define.amd)
define(['jquery'], factory);
else
factory(jQuery);
}(function ($) {
'use strict';
// This is the plugin proper.
$.fn.myMethod = function(/* ... */) {
// Code for the method...
};
}));
需要其他东西而不只是 jQuery 的插件将使用上面的结构并进行以下修改:
A plugin that needs other things than just jQuery would use the structure above with the following modifications:
调用
define
列出所需的附加模块.
A call to
define
that lists the additional modules needed.
一个 factory(jQuery)
调用(在非 AMD 分支中,在 RequireJS 未加载插件时使用)在 jQuery
之后从全局空间传递附加值代码>.
A factory(jQuery)
call (in the non AMD branch, used when RequireJS is not loading the plugin) that passes additional values from the global space after jQuery
.
一个工厂函数function ($)
,它有额外的参数来接收传递给它的额外值.
A factory function function ($)
that has additional arguments to receive the additional values passed to it.
因此,如果插件需要模块 foo
,它在全局空间中将自身导出为 foo
并使用 RequireJS 配置将其命名为 "foo"
,然后:
So if the plugin needs module foo
which exports itself in the global space as foo
and with a RequireJS configuration that names it "foo"
, then:
(function (factory) {
// If in an AMD environment, define() our module, else use the
// jQuery global.
'use strict';
if (typeof define === 'function' && define.amd)
define(['jquery', 'foo'], factory);
else
factory(jQuery, foo);
}(function ($, foo) {
'use strict';
// This is the plugin proper.
$.fn.myMethod = function(/* ... */) {
// Code for the method...
foo.blah();
};
}));
这篇关于我可以编写一个 javascript 文件,在它可用时选择使用 require.js 来指定依赖项吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!