我最近几天一直在尝试使用RequireJS,试图理解define和require之间的区别。
define似乎允许模块分离,并允许遵循依赖关系顺序。 但是它会先下载所有需要的文件。 而require仅在需要时加载所需内容。
这两者可以一起使用吗?每个应该用于什么目的?
define
,您可以在require.js中注册一个模块,您可以在其他模块定义或require语句中依赖该模块。
使用require
,您可以“只是”加载/使用可以由require.js加载的模块或JavaScript文件。
有关示例,请参阅文档
我的经验法则:
Define:如果您要声明应用程序的其他部分将依赖的模块。
Require:如果您只想加载和使用东西。
以下内容摘自require.js的源代码(第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的字符串和所需模块的数组)和一个必需参数(工厂方法)。工厂方法MUST 返回你的模块实现(与模块模式方式相同)。
require()
函数不必返回新模块的实现。define()
时,您正在请求类似于“运行我作为参数传递的函数并将其返回给我传递的ID,但是在此之前,请检查这些依赖项是否已加载”的内容。require()
时,您正在说类似于“我传递的函数具有以下依赖关系,请在运行它之前检查这些依赖关系是否已加载”。
require()
函数是您使用定义的模块的地方,以确保模块已定义,但您不会在那里定义新模块。一般规则:
You use define when you want to define a module that will be reused
You use require to simply load a dependency
//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
});
“define”方法用于简化模块定义,而“require”方法则用于处理依赖项加载。
使用以下签名基于提案使用“define”来定义命名或未命名的模块:
define(
module_id /*optional*/,
[dependencies] /*optional*/,
definition function /*function for instantiating the module or object*/
);
相对而言,require通常用于在顶级JavaScript文件中加载代码或在模块内部加载代码以便您可以动态获取依赖项。
require()和define()都用于加载依赖项。这两种方法之间有一个重要的区别。
非常简单
require():该方法用于运行即时功能。 define():该方法用于定义可在多个位置(重用)中使用的模块。
define()
的函数),直到有一个要求它或依赖于它的require([])
调用。" https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.0#delayed - alxndr