RequireJS - jQuery Using Shim Config



jQuery uses shim configuration to define the dependencies for jQuery plugins and set a module value by declaring dependencies.

Loading jQuery

require(['jquery','jquery.myjsfile1','jquery.myjsfile2'], function($) {
   $(function() {
      //code here
   });
});

Example

The following example uses shim configuration to define the dependencies for jQuery plugins. Create a html file with the name index.html and place the following code in it −

<!DOCTYPE html>
<html>
   <head>
      <title>jQuery Shim Config</title>
      <script data-main = "app" src = "lib/require.js"></script>
   </head>
   
   <body>
      <h2>jQuery Shim Config</h2>
      <p>Welcome to Tutorialspoint!!!</p>
   </body>
</html>

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

//You can configure loading modules from the lib directory
requirejs.config ({
   "baseUrl": "lib",
   
   "paths": {
      "app": "../app"
   },
   
   "shim": {
      "jquery.shim1": ["jquery"],
      "jquery.shim2": ["jquery"]
   }
});

//To start the application, load the main module from app folder
requirejs(["app/main"]);

Create a folder called app and load the main.js module from this folder −

define(["jquery", "jquery.shim1", "jquery.shim2"], function($) {
   //loading the jquery.shim1.js and jquery.shim2.js plugins 
   $(function() {
      $('body').shim1().shim2();
   });
});

Create one more folder called lib to store the require.js file and other js files as shown below −

lib/jquery.shim1.js

$.fn.shim1 = function() {
   return this.append('<p>This is shim1 config...!</p>');
};

lib/jquery.shim2.js

$.fn.shim2 = function() {
   return this.append('<p>This is shim2 config...!</p>');
};

Output

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

RequireJS Shim Config
requirejs_jquery.htm
Advertisements