Skip to main content

31 Best RequireJs Interview Questions and Answers

What is RequireJS?
ü  RequireJS is a JavaScript library and AMD compatible asynchronous module loader.
ü  RequireJS is used to loads the JavaScript files and resolve their dependencies and its supported to the latest versions of popular browsers.
ü  RequireJS helps to improve the performance and code of quality.
ü  RequireJS was developed by David Mark. Its open source and it was released in 2009.
ü  RequireJS is used by node.js to fetch and load module.
ü  RequireJS contains a small set of plugins which allow us to loading the various types of resources like text, Dom Ready, i18n, CSS and loading.

RequireJS includes three main API functions -
ü  Define () - This function is used to define a module. Each module is defined a unique module ID. This module Id is used by RequireJS at the runtime.
ü  Require () - This function is used to load dependencies and It is a global function.
ü  Config () - This function is used to configure the RequireJS runtime functionality.

How to Install RequireJS?
You can install the latest release of RequireJS from the command prompt using the below commands-
//Install the RequireJS package
npm install -g requirejs



Why do People use RequireJS? What Are the Benefits?
ü  It is an open source JavaScript library.
ü  It is AMD compatible asynchronous module loader.
ü  It is Asynchronous by nature.
ü  Lazy loaded on-demand.
ü  It is easily portable.
ü  It is Avoids global variables.
ü  It has ability to load nested dependencies.
ü  Its Dependencies are easy to identify.
ü  It can be easily configured.
ü  It can load multiple versions of the same library.
ü  It will make the website more optimize and speed.

How To define entry point for RequireJS?

We need to define an html file and it could be "index.html" where RequireJS is loading i.e.
<!DOCTYPE html>
<html>
<head>
    <script data-main="libs/main" src="libs/require.js"></script>
</head>
<body>
    <h1> RequireJS Sample apps</h1>
</body>
</html>

In above example, the data-main attribute of require.js will start initialisation of files.

What Are the main Features of RequireJS?
ü  RequireJS manages the dependencies between JavaScript files and improves the quality of the code and application speed.
ü  It is combines and minifies the modules into one script for speed-up.
ü  RequireJS Collecting the different JavaScript files from different modules at the compilation time.
ü  Easy debugging
ü  Lesser HTTP requests
ü  Reduce code Complexity in large application.
ü  And so on.

What Are disadvantage of RequireJS?
ü  No support for AMD in Node.js
ü  Not all modules implement AMD


When Should I use require () and when to use define ()?
The define () method looks like -
ü  The define () method is used for facilitating module definition
ü  The define () method accepts two optional parameters module ID and array of required modules [dependencies]
ü  The define() method MUST return the implementation for your module i.e.

define(
  module_id /*optional*/,
  [dependencies] /*optional*/,
  definition function /*function for instantiating the module or object*/
);

And
define(['moduleA', 'moduleB'], function (moduleA, moduleB) {
  //define the module value by returning a value
  return function () {};
});

The require () method looks like -
ü  The require () method is used for handling dependency loading
ü  The require () function doesn't have to return the implementation of a new module.

require(['jquery'], function ($) {
  //jQuery was loaded and can be used now.
});

Example 1 -
define( 'MyApp', ["marionette"], function (Marionette) {
      // set up the app instance
      var app = new Marionette.Application();
      app.on("initialize:after", function(){
        console.log("initialize started.");
      });

      // export the app from this module
      return app;
});

Example 2 -
// Fetch and execute Marionette App
require( ["MyApp"], function (app) {
  // Execute App
   app.start();
});

Example 3 -
define({
  "root": {
     "india": "india",
     "australia": "australia",
     "england": "england"
  }
});

What Are Asynchronous Module Definition (AMD) Modules?
Defining Modules -The Module is defined using define () method and it used for loading the module i.e.
define({
  country:"India",
  state: "UP",
  city: "Noida",
  userDetail: function () {
           return "User Detail";
    }
});

Defining Functions - A module can also use a function without dependencies i.e.
define(function () {
    return {
        country:"India",
        state: "UP",
        city: "Noida"
    }
});

Defining Functions with Dependencies - The Dependencies module looks like.
define(["../comp", "../user"],
  function(comp, user) {
      return {
          country:"India",
          state: "UP",
          city: "Noida",     
          addUser: function() {
            comp.decrement(this);
            user.add(this);
          }     
      }
});

Defining a Module as a Function - Its looks like.
define(["../comp", "../user"],
    function(comp, user) {
      return function(userName){
          return userName != null ? userName :'NA'
      }
});

Defining a Module with a Name - Its looks like.
define("Users", ["../comp", "../user"],
  function(comp, user) {
    return {
        country:"India",
        state: "UP",
        city: "Noida",     
        addUser: function() {
          console.log(this);
        }     
    }
});

What Is config function?
The RequireJS can be initialized by passing the main configuration in the HTML template through the data-main attribute.

If you want to update the RequireJS configuration values with your own configurations value. You can do using the requirejs.config function. The configurations options -
ü  config - This is for configuration to a module by using the config option
ü  baseUrl -This is the root path to start the loading of modules.
ü  paths - this is the path mapping for modules that don’t exists in under the base URL.
ü  Shims - This is use for configuration for dependencies.
ü  deps  - array of dependencies to load
ü  map  -
ü  urlArgs -This is the query string arguments are used to fetch all resources that are loaded by using RequireJS.
ü  callback -It executes a function after loading the dependencies and is required when Require is specified as config object before loading RequireJS.
ü  xhtml - It is used to create the script elements by using the document.createElementNS() method.
ü  scriptType - It defines the value for script type attribute used in the document. Default type is "text/javascript".

Example looks like-
require.config({
    baseUrl: 'scripts/app',
    paths: {
        lib: '../lib'
    },
    shim: {
        'backbone': {
            deps: ['underscore'],
            exports: 'Backbone'
        }
    }
});

What Is the project structure of RequireJs?
Project directory and the structure looks like-
── app.js
── index.html
── lib
│   ── modules
│   │   └── template.js
│   ── require.js
│   ── jquery.js
│   └── underscore.js

What Is module in RequireJs?
Module is independent unit of program which make easy maintenance and reusability of code. In RequireJs we talk about JavaScript module.

What is data-main attribute?
The data-main attribute is an attribute that RequireJS will check to start script loading. The data-main set to the base URL for all the scripts.

Example -
<!DOCTYPE html>
<html>
<head>
    <script data-main="libs/main" src="libs/require.js"></script>
</head>
<body>
    <h1> RequireJS Sample apps</h1>
</body>
</html>

What Is AMD module?
The AMD is stands for Asynchronous Module Definition and is used for defining modules and their dependencies with asynchronously manner.

How To use RequireJs with jQuery?
The RequireJS uses jQuery and lots of another dependency i.e.
require(['jquery'], function ($) {
  //jQuery was loaded and can be used now.
});

What is the role of Optimizer?
The Optimizer is a built process where your project is deployed to end user and its combines all scripts/css files together and minify them.

I hope you are enjoying with this post! Please share with you friends!! Thank you!!!
By Anil Singh | Rating of this article (*****)

Popular posts from this blog

List of Countries, Nationalities and their Code In Excel File

Download JSON file for this List - Click on JSON file    Countries List, Nationalities and Code Excel ID Country Country Code Nationality Person 1 UNITED KINGDOM GB British a Briton 2 ARGENTINA AR Argentinian an Argentinian 3 AUSTRALIA AU Australian an Australian 4 BAHAMAS BS Bahamian a Bahamian 5 BELGIUM BE Belgian a Belgian 6 BRAZIL BR Brazilian a Brazilian 7 CANADA CA Canadian a Canadian 8 CHINA CN Chinese a Chinese 9 COLOMBIA CO Colombian a Colombian 10 CUBA CU Cuban a Cuban 11 DOMINICAN REPUBLIC DO Dominican a Dominican 12 ECUADOR EC Ecuadorean an Ecuadorean 13 EL SALVADOR

39 Best Object Oriented JavaScript Interview Questions and Answers

Most Popular 37 Key Questions for JavaScript Interviews. What is Object in JavaScript? What is the Prototype object in JavaScript and how it is used? What is "this"? What is its value? Explain why "self" is needed instead of "this". What is a Closure and why are they so useful to us? Explain how to write class methods vs. instance methods. Can you explain the difference between == and ===? Can you explain the difference between call and apply? Explain why Asynchronous code is important in JavaScript? Can you please tell me a story about JavaScript performance problems? Tell me your JavaScript Naming Convention? How do you define a class and its constructor? What is Hoisted in JavaScript? What is function overloadin

React | Encryption and Decryption Data/Text using CryptoJs

To encrypt and decrypt data, simply use encrypt () and decrypt () function from an instance of crypto-js. Node.js (Install) Requirements: 1.       Node.js 2.       npm (Node.js package manager) 3.       npm install crypto-js npm   install   crypto - js Usage - Step 1 - Import var   CryptoJS  =  require ( "crypto-js" ); Step 2 - Encrypt    // Encrypt    var   ciphertext  =  CryptoJS . AES . encrypt ( JSON . stringify ( data ),  'my-secret-key@123' ). toString (); Step 3 -Decrypt    // Decrypt    var   bytes  =  CryptoJS . AES . decrypt ( ciphertext ,  'my-secret-key@123' );    var   decryptedData  =  JSON . parse ( bytes . toString ( CryptoJS . enc . Utf8 )); As an Example,   import   React   from   'react' ; import   './App.css' ; //Including all libraries, for access to extra methods. var   CryptoJS  =  require ( "crypto-js" ); function   App () {    var   data

25 Best Vue.js 2 Interview Questions and Answers

What Is Vue.js? The Vue.js is a progressive JavaScript framework and used to building the interactive user interfaces and also it’s focused on the view layer only (front end). The Vue.js is easy to integrate with other libraries and others existing projects. Vue.js is very popular for Single Page Applications developments. The Vue.js is lighter, smaller in size and so faster. It also supports the MVVM ( Model-View-ViewModel ) pattern. The Vue.js is supporting to multiple Components and libraries like - ü   Tables and data grids ü   Notifications ü   Loader ü   Calendar ü   Display time, date and age ü   Progress Bar ü   Tooltip ü   Overlay ü   Icons ü   Menu ü   Charts ü   Map ü   Pdf viewer ü   And so on The Vue.js was developed by “ Evan You ”, an Ex Google software engineer. The latest version is Vue.js 2. The Vue.js 2 is very similar to Angular because Evan You was inspired by Angular and the Vue.js 2 components looks like -

Encryption and Decryption Data/Password in Angular

You can use crypto.js to encrypt data. We have used 'crypto-js'.   Follow the below steps, Steps 1 –  Install CryptoJS using below NPM commands in your project directory npm install crypto-js --save npm install @types/crypto-js –save After installing both above commands it looks like  – NPM Command  1 ->   npm install crypto-js --save NPM Command  2 ->   npm install @types/crypto-js --save Steps 2  - Add the script path in “ angular.json ” file. "scripts" : [                "../node_modules/crypto-js/crypto-js.js"               ] Steps 3 –  Create a service class “ EncrDecrService ” for  encrypts and decrypts get/set methods . Import “ CryptoJS ” in the service for using  encrypt and decrypt get/set methods . import  {  Injectable  }  from   '@angular/core' ; import   *   as   CryptoJS   from   'crypto-js' ; @ Injectable ({    providedIn:   'root' }) export   class   EncrDecrS