35

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

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

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

Any use cases would be very helpful..

isherwood
  • 58,414
  • 16
  • 114
  • 157
copenndthagen
  • 49,230
  • 102
  • 290
  • 442

5 Answers5

53

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

As long as there is only one define per file, it will register that module as available under that filename. However, define modules are only loaded once a require function asks for each of them.

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

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

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

// 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:

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 manually include 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.

Katana314
  • 8,429
  • 2
  • 28
  • 36
  • 1
    Thx for your answer...Could you please elaborate with a basic example... – copenndthagen Sep 02 '13 at 07:16
  • 1
    @Katana314...could u pls elaborate... – copenndthagen Sep 03 '13 at 11:35
  • 1
    @testndtv Added an example; hope it helps. – Katana314 Sep 03 '13 at 15:38
  • Minor point: since /company/welcomepage.js declares a dependency on 'company/ui_library', the file that will get loaded is /company/company/ui_library.js -- is that what you intended? – Don Hatch Feb 12 '17 at 08:49
  • Having trouble reproducing "If that's the only Javascript file, ... there would be nothing in the console log" in chrome 57.0.2987.37, requirejs 2.3.2. Obviously that can't be the *only* javascript file; you need require.js. If my html says ``, I get `Uncaught Error: Mismatched anonymous define() module: function (uiLib) { console.log('Welcome to {company}!'); }`. If my html says ``, I do get the console message. Can you give a complete example? – Don Hatch Feb 12 '17 at 09:04
  • 1
    @DonHatch On first point: AMD can be configured to either always start from a certain root path, or recognize a certain folder name as having a certain home (eg, "jquery" is in "apis.google.com/cdn/jquery"). On second example: This error did not occur for me when testing against requirejs 2.1.5 or in Dojo. If you're correct, it's possible it has changed behavior since then; maybe as a way of helping people catch issues like this one early, before they're confused by it. In your third example (`data-main`) this is explicitly requiring the file, and so it decides to run it. – Katana314 Feb 13 '17 at 21:46
24

require and requirejs are the same.

require === requirejs // true

require is a way to load a module which has been defined. For example to load the logger module I could do:

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

Here i am calling require, specifying an already defined module called logger and using it by calling its bla method.

define is a way to define a module. For example to define a logger module I could do:

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

Here I called define and defined the logger module. in this module I returned the bla function I want to expose.

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 logger module, this time using a module:

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

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

danronmoon
  • 3,814
  • 5
  • 34
  • 56
user566245
  • 4,011
  • 1
  • 30
  • 36
  • no where other than your comment does it say 'logger' - so what defines it as the 'logger' module? The comment or the filename? – Scott Jul 09 '18 at 17:47
  • Excellent answer. I've been coding in Javascript for a couple a years and have always found it confusing compared to Java for Object Oriented Programming. You answer is succinct and just what I needed to hear to clarify using requireJS for modules (instead of the usual raw immediately invoking functions way) – kiwicomb123 Aug 26 '18 at 13:03
  • @Scott probably very late to the party. The actual AMD syntax is: `define(id?, dependencies?, factory);` where if no module name (the `id` argument) is specified then the module name is its file location. – Advena Dec 16 '21 at 15:25
1

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:

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

Maybe you got mixed up with the JSONP service dependency format, 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.

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

Joni Bekenstein
  • 331
  • 1
  • 7
-1

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

whereas ..

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

Rajdeep Sharma
  • 463
  • 1
  • 5
  • 9
-4

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

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).

Baalu
  • 243
  • 2
  • 9