Basic use of AMD - requireJS in JavaScript modular programming

Keywords: Javascript JQuery Vue Programming

AMD of JavaScript modular programming

requireJS basic use

Tags (space delimited): JavaScript

Reference article

AMD specification

AMD is the abbreviation of "Asynchronous Module Definition", which means "Asynchronous Module Definition". It loads the module asynchronously, and the loading of the module does not affect the running of the subsequent statements. All statements that depend on this module are defined in a callback function, which will not run until the loading is completed.

Function of require.js

  • Realize the asynchronous loading of js file to avoid the web page losing response;
  • Manage the dependencies between modules to facilitate the code writing and maintenance.

First, introduce the requireJS file, and specify the entry file (main module) on the script tag:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>javascript Modular programming</title>

<script type="text/javascript" src="" defer async data-main="js/main.js"></script>

Next, you need to configure main.js:

// Module loaded configuration
    // Base directory if each module is not in a base directory
    // Specify directly in paths without baseUrl
    baseUrl: "lib",
    paths: {
        'jquery': 'jquery',
        'vue': 'vue.min',
        'pagination': 'my-pager'

    // The ship property is used to configure incompatible modules. Each module is defined as follows:
    // (1) The exports value (the variable name of the output) indicates the name of the external call to this module
    // (2) The DEPs array indicates the dependency of the module
    // For example, jq plug-ins can be defined in this way
    shim: {
        'jquery.scroll': {
            deps: ['jquery'],
            exports: 'jQuery.fn.scroll'

    // requireJS also has a series of plug-ins
    // [Plugins](

// The main module depends on other modules, so you need to use the require() function defined by the AMD specification
// require([modules], function (modules) { });
require(['jquery', 'vue', 'pagination'], function ($, Vue, pagination) {

For example, pagination in the above example:

;(function (factory) {
    if (typeof exports === 'object') {
        // Node/CommonJS
        factory(require('document'), require('window'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD
        define(factory(document, window));
    } else {
        // Browser globals
        factory(document, window);
}(function (document, window) {
    var Test = {
        a: 1

    if (typeof module != 'undefined' && module.exports) {
        module.exports = Test;
    } else if (typeof define == 'function' && define.amd) {
        define(function () { return Test; });
    } else {
        window.Test = Test;

Source address

The end...    Last updated by: Jehorn, Jan 04, 2018, 10:35 AM

Posted by nlhowell on Thu, 30 Apr 2020 07:59:20 -0700