我何时应该使用require()以及何时使用define()?

时间:2012-02-29 22:24:23

标签: require requirejs

过去几天我一直在玩requirejs。我试图理解define和require之间的区别。

定义似乎允许模块分离并允许遵守依赖性排序。但它会下载所需的所有文件。虽然只需要在您需要时加载您需要的东西。

这两者是否可以一起使用,是否应该使用它们?

5 个答案:

答案 0 :(得分:326)

来自require.js source code(第1902行):

/**
 * The function that handles definitions of modules. Differs from
 * require() in that a string for the module should be the first argument,
 * and the function to execute after dependencies are loaded should
 * return a value to define the module corresponding to the first argument's
 * name.
 */

define() 函数接受两个可选参数(表示模块ID和所需模块数组的字符串)和一个必需参数(工厂方法)。

返回工厂方法必须返回模块的实现(与Module Pattern一样)。

require() 函数不必返回新模块的实现。

使用 define() ,你会问一些像“运行我作为参数传递的函数并将任何返回值分配给我传递的ID,但之前,检查这些依赖项是否已加载“

使用 require() ,你会说“我传递的函数具有以下依赖关系,检查这些依赖项是否在运行之前加载”

require() 函数是您使用已定义模块的位置,以确保模块已定义,但您没有在那里定义新模块。

答案 1 :(得分:324)

使用define在require.js中注册一个模块,然后您可以依赖于其他模块定义或require语句。 使用require,您“只”加载/使用可由require.js加载的模块或javascript文件。 有关示例,请查看documentation

我的经验法则:

  • 定义:如果要声明模块,应用程序的其他部分将依赖于。

  • 要求:如果您只想加载和使用内容。

答案 2 :(得分:2)

“定义”促进模块定义的方法 和 处理依赖性加载的“require”方法

define用于根据提议使用以下签名定义命名或未命名的模块:

define(
module_id /*optional*/, 
[dependencies] /*optional*/, 
definition function /*function for instantiating the module or object*/
);
另一方面,

require通常用于在顶层JavaScript文件或模块内加载代码,如果您希望动态获取依赖项

有关详细信息,请参阅https://addyosmani.com/writing-modular-js/

答案 3 :(得分:2)

require()和define()都用于加载依赖项。这两种方法之间存在重大差异。

非常简单的家伙

Require():方法用于运行直接功能。 define():Method用于定义在多个位置使用的模块(重用)。

答案 4 :(得分:1)

一般规则:

  1. 当您要定义要重用的模块时,请使用define

  2. 您可以使用require来简单地加载依赖项

    //sample1.js file : module definition 
    define(function() {
          var sample1 = {};
          //do your stuff
         return sample1;
     });
    
    //sample2.js file : module definition and also has a dependency on jQuery and sample1.js
    define(['jquery', 'sample1'], function($,sample1) {
        var sample2 = {
            getSample1:sample1.getSomeData();
        };
        var selectSomeElement = $('#someElementId');
        //do your stuff....
        return sample2;
    });
    
    //calling in any file (mainly in entry file)
    require(['sample2'], function(sample2) {
        // sample1 will be loaded also
    });
    

希望这对您有所帮助。