Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between require() and define() in RequireJS? [duplicate]

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

like image 318
copenndthagen Avatar asked Aug 30 '13 14:08

copenndthagen


People also ask

What is define in RequireJS?

The define() function can be used to load the modules (module can be an object, function, class or a code which is executed after loading a module). You can load different versions of the same module in the same page.

What is the use of require ()?

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

What is return type of require?

The require(...) function returns the module. exports value from the "required" module, and in the case its the Profile function.

Can I use require in js file?

With require , you can include them in your JavaScript files and use their functions and variables. However, if you are using require to get local modules, first you need to export them using module.


1 Answers

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.

like image 137
Katana314 Avatar answered Sep 25 '22 23:09

Katana314