我是否可以编写一个javascript文件,该文件可选地使用require.js来指定依赖项何时可用? [英] Can I write a javascript file that optionally uses require.js to specifies dependencies when it is available?

查看:70
本文介绍了我是否可以编写一个javascript文件,该文件可选地使用require.js来指定依赖项何时可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个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模块工作,并指定其依赖项。可以这样做,还是垫片是唯一的方法呢?

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:


  1. 调用定义,列出所需的其他模块。

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆