RequireJS - Defining Function



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. The different versions can be analyzed in the same order, even if they are loaded in a different order.

Syntax

define(['module1', 'module2'], function (module1, module2) {
   //define the module value by returning a value
   return function () {};
});

You can pass a list of module names when you define a module and RequireJS can be used to retrieve these modules before executing the module. These modules can be passed as parameters of the definition function.

Example

The following example shows the usage of the define() function while loading the modules. Create an html file with the name index.html and place the following code in it −

<!DOCTYPE html>
<html>
   <head>
      <title>Define() Function</title>
      <script data-main = "main" src = "require.js"></script>
   </head>
   
   <body>
      <h2>RequireJS Define() Function Example</h2>
   </body>
</html>

Create a js file with the name main.js and add the following code in it −

define(function (require) {
   var myteam = require("./team");
   var mylogger = require("./player");
   alert("Player Name : " + myteam.player);
   mylogger.myfunc();
});

Now, create two more js files with the names team.js and player.js and place the following code respectively −

team.js

define({
   player: "Sachin Tendulkar",
   team : "India"
});

player.js

define(function (require) {
   var myteam = require("./team");

   return {
      myfunc: function () {
         document.write("Name: " + myteam.player + ", Country: " + myteam.team);
      }
   };
});

Output

Open the HTML file in a browser; you will receive an output as in the following screenshot −

RequireJS Define Function

Click on the "OK" button, you will get another output from modules −

RequireJS Define Function
Advertisements