javascript RequireJS 中的 require() 和 define() 的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18534912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:18:46  来源:igfitidea点击:

Difference between require() and define() in RequireJS?

javascriptrequirejsamd

提问by testndtv

In RequireJS, what is the basic difference between using require() Vs define();

在RequireJS中,使用require()和define()的基本区别是什么;

require(['a'], function(a) {
    // some code
});

// A.js
define(['b','c','d','e'], function() {
    //some code
});

Any use cases would be very helpful..

任何用例都会非常有帮助..

回答by Katana314

One core difference that annoyed me in early use was figuring out that a definemight never be called.

在早期使用中让我烦恼的一个核心区别是弄清楚 adefine可能永远不会被调用

As long as there is only one defineper file, it will register that module as available under that filename. However, definemodules are only loaded once a requirefunction asks for each of them.

只要define每个文件只有一个,它就会将该模块注册为该文件名下的可用模块。但是,define模块仅在require函数要求每个模块时加载。

Define: If you need a XXX, then load these other things first, then return the result of this function.

定义:如果你需要一个XXX,那么先加载这些其他的东西,然后返回这个函数的结果。

Require: Load these other things, then run this function. (no "if")

要求:加载这些其他东西,然后运行这个函数。(没有“如果”)

Example: Let's say you include this JS file in your page:

示例:假设您在页面中包含此 JS 文件:

// this is in company/welcomepage.js
define(['company/ui_library'],
    function(uiLib) {
        console.log('Welcome to {company}!');
    }
);

If that's the only Javascript file, you could open your page, and there would be nothing in the console log, in spite of the script telling it to welcome the user. However, that changes if somewhere in the page, or in another script, you insert the following:

如果这是唯一的 Javascript 文件,您可以打开您的页面,并且控制台日志中不会有任何内容,尽管脚本告诉它欢迎用户。但是,如果在页面的某处或另一个脚本中插入以下内容,情况会发生变化:

require(['company/welcomepage'], function() {
    // optionally insert some other page-initialization logic here
});

Now, the page will put a welcome message in the console when it loads.

现在,页面将在加载时在控制台中放置一条欢迎消息。

In fact, with that second one in place, there would be no need to manuallyinclude welcomepage.js as a <script>tag; it would load it from its location as soon as it sees the require, and realizes it needs it.

事实上,有了第二个,就不需要手动包含welcomepage.js 作为<script>标签;它会在看到需求后立即从其位置加载它,并意识到它需要它。

回答by user566245

requireand requirejsare the same.

require并且requirejs是一样的。

require === requirejs // true

requireis a way to load a module which has been defined. For example to load the loggermodule I could do:

require是一种加载已定义模块的方法。例如加载logger我可以做的模块:

require(["logger"], function(logger){
  logger.bla("S");
});

Here i am calling require, specifying an already defined module called loggerand using it by calling its blamethod.

在这里,我正在调用require,指定一个已定义的模块logger,并通过调用其bla方法来使用它。

defineis a way to define a module. For example to define a loggermodule I could do:

define是一种定义模块的方法。例如定义一个logger我可以做的模块:

// logger.js
define(function(){
  return {
    bla: function(x){
      alert(x);
    }
  }
});

Here i called defineand defined the loggermodule. in this module I returned the blafunction i want to expose.

在这里我调用define并定义了logger模块。在这个模块中,我返回了bla我想要公开的函数。

Sometimes define looks very similar to exports because define can also depend and use other modules just like require can use other modules. Let me show you the same loggermodule, this time using a module

有时define看起来与exports非常相似,因为define也可以依赖和使用其他模块,就像require可以使用其他模块一样。让我向您展示相同的logger模块,这次使用模块

// logger.js
define(["popup"], function(popup){
  return {
    bla: function(x){
      popup.show(x);
    }
  }
});

Here the logger module I defined, also has a dependency called popupand thus it looks like require.

这里的记录器模块 Idefined也有一个依赖项popup,因此它看起来像require.

回答by Joni Bekenstein

I believe you always use define for your module definitions. You have several flavours to do so, you can define a module with its dependencies in an array as the first argument to define (as in the example you posted).

我相信你总是为你的模块定义使用定义。您有几种方法可以这样做,您可以在数组中定义一个模块及其依赖项作为要定义的第一个参数(如您发布的示例中所示)。

Or you can use the Simplified CommonJS wrapper, something like this:

或者您可以使用Simplified CommonJS 包装器,如下所示:

define(function (require) {
    var otherModule = require('otherModule');
    return function () {
        return otherModule.operation();
    };
});

Maybe you got mixed up with the JSONP service dependencyformat, which uses require() to load the service, and then specify define() as the JSONP callback which will eventually define the module once the service responds.

也许你混淆了JSONP 服务依赖格式,它使用 require() 加载服务,然后指定 define() 作为 JSONP 回调,一旦服务响应,它将最终定义模块。

So in the end, you use define() to define modules, and require() to load them.

所以最后,你使用 define() 来定义模块,并使用 require() 来加载它们。

回答by Rajdeep Sharma

defineis how we declare a module, in accordance with AMDmodule format(there are other available module formats like CommonJS, ES2015, System.register, UMD)

定义是我们如何声明一个模块,按照AMD模块格式(还有其他可用的模块格式,如CommonJSES2015System.registerUMD

whereas ..

然而 ..

requireis a module loading construct that's available with module loaders like RequireJs, SystemJS, Node'sbuilt-in module loader. It is used when you want to use a module defined in one of the above-stated module formats.

require是一种模块加载构造,可用于模块加载器,如RequireJsSystemJSNode 的内置模块加载器。当您想要使用以上述模块格式之一定义的模块时使用它。

回答by Baalu

require()and define()both used to load dependencies.There is a major difference between these two method.

require()define()都用于加载依赖。这两种方法有一个主要区别。

Its very Simple Guys

它非常简单的家伙

Require():Method is used to run immediate functionalities. define():Method is used to define modules for use in multiple locations(reuse).

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