search
HomeWeb Front-endJS TutorialWhat is modular programming? Summary of js modular programming

1 What is modular programming

2 Why should we modularize

3 AMD

4 CommonJS

5 Summary

To understand a technology, you must first understand the background of the technology and the problems it solves, rather than simply knowing how to use it. The previous state may have been to understand just for the sake of understanding, without knowing the actual causes and benefits, so let’s summarize it today.

1 What is modular programming

Let’s look at Baidu Encyclopedia’s definition

Modular programming refers to dividing a large program according to its functions during programming It is divided into several small program modules, each small program module completes a certain function, and the necessary connections are established between these modules, and the entire function is completed through the mutual cooperation of the modules.

For example, java's import, C#'s using. My understanding is that through modular programming, different functions can be separated, and modification of one function will not affect other functions.

2 Why modularize

Let’s look at the following example

// A.jsfunction sayWord(type){
    if(type === 1){
        console.log("hello");
    }else if(type === 2){
        console.log("world");
    }
}// B.jsfunction Hello(){
    sayWord(1);
}// C.jsHello()

Assume that among the above three files, B.js references the content in A.js, and C.js The content in B.js is also quoted. If the person writing C.js only knows that B.js is quoted, then he will not quote A.js, which will cause a program error, and the reference order of the files cannot be wrong. It brings inconvenience to the debugging and modification of the overall code.

There is another problem. The above code exposes two global variables, which can easily cause pollution of global variables

3 AMD

AMD is Asynchronous Module Definition (asynchronous module definition) . The module is loaded asynchronously. The loading of the module will not affect the execution of subsequent statements.

Assume the following situation

// util.jsdefine(function(){
    return {
        getFormatDate:function(date,type){
            if(type === 1){                return '2018-08-9'
            }            if(type === 2){                return '2018 年 8 月 9 日'
            }
        }
    }
})// a-util.jsdefine(['./util.js'],function(util){
    return {
        aGetFormatDate:function(date){
            return util.getFormatDate(date,2)
        }
    }
})// a.jsdefine(['./a-util.js'],function(aUtil){
    return {
        printDate:function(date){
            console.log(aUtil.aGetFormatDate(date))
        }
    }
})// main.jsrequire(['./a.js'],function(a){
    var date = new Date()
    a.printDate(date)
})
console.log(1);// 使用// <script src = "/require.min.js" data-main="./main.js"></script>

The page will print 1 first, and then August 9, 2018 will be printed. Therefore, the loading of AMD will not affect subsequent statement execution.

What will happen if it is not loaded asynchronously

var a = require(&#39;a&#39;);
console.log(1)

The following statements need to wait for a to be loaded before they can be executed. If the loading time is too long, the entire program will be stuck here. Therefore, the browser cannot load resources synchronously, which is also the background of AMD.

AMD is a specification for modular development on the browser side. Since this specification is not originally supported by JavaScript, third-party library functions, namely RequireJS, need to be introduced when developing using the AMD specification.

RequireJS main problems solved

  • Enable JS to be loaded asynchronously to avoid page loss of response

  • Manage dependencies between codes sex, which is conducive to code writing and maintenance

Let’s take a look at how to use require.js

If you want to use require.js, you must first define

// ? 代表该参数可选
    define(id?, dependencies?, factory);
  • id: refers to the name of the defined module

  • dependencies: is an array of modules that the defined module depends on

  • factory: Initialize the function or object to be executed for the module. If it is a function, it should be executed only once. If it is an object, this object should be the output value of the module.

    For specific specifications, please refer to AMD (Chinese version)
    For example, create a module named "alpha", use require, exports, and a module named "beta":

define("alpha", ["require", "exports", "beta"], function (require, exports, beta) {
       exports.verb = function() {
           return beta.verb();           //Or:
           return require("beta").verb();
       }
   });

An anonymous module that returns objects:

define(["alpha"], function (alpha) {
       return {
         verb: function(){
           return alpha.verb() + 2;
         }
       };
   });

A module with no dependencies can directly define objects:

define({
     add: function(x, y){
       return x + y;
     }
   });

How to use

AMD uses the require statement to load the module

require([module],callback);
  • module: is an array, the members inside are the modules to be loaded

  • callback: load Callback function after success

For example

require([&#39;./a.js&#39;],function(a){
    var date = new Date()
    a.printDate(date)
})

The specific usage method is as follows

// util.jsdefine(function(){
    return {
        getFormatDate:function(date,type){
            if(type === 1){                return '2018-08-09'
            }            if(type === 2){                return '2018 年 8 月 9 日'
            }
        }
    }
})// a-util.jsdefine(['./util.js'],function(util){
    return {
        aGetFormatDate:function(date){
            return util.getFormatDate(date,2)
        }
    }
})// a.jsdefine(['./a-util.js'],function(aUtil){
    return {
        printDate:function(date){
            console.log(aUtil.aGetFormatDate(date))
        }
    }
})// main.jsrequire([&#39;./a.js&#39;],function(a){
    var date = new Date()
    a.printDate(date)
})// 使用// 

Assume there are 4 files here, util.js, a- util.js refers to util.js, a.js refers to a-util.js, and main.js refers to a.js.

Among them, the data-main attribute is used to load the main module of the web page program.

The above example demonstrates the simplest way to write a main module. By default, require.js assumes that dependencies are in the same directory as the main module.

Use the require.config() method to customize the loading behavior of the module. require.config() It is written at the head of the main module (main.js). The parameter is an object. The paths attribute of this object specifies the loading path of each module.

require.config({
    paths:{        "a":"src/a.js",        "b":"src/b.js"
    }
})

There is also a The first method is to change the base directory (baseUrl)

require.config({

    baseUrl: "src",

    paths: {

      "a": "a.js",
      "b": "b.js",

    }

  });

4 CommonJS

commonJS is the modular specification of nodejs. It is now widely used in the front end. Due to the high degree of automation of the build tool, the use of npm The cost is very low. commonJS does not load JS asynchronously, but loads it synchronously in one go.

In commonJS, there is a global method require(), which is used to load modules, such as

const util = require(&#39;util&#39;);

Then, just You can call the methods provided by util

const util = require(&#39;util&#39;);var date = new date();
util.getFormatDate(date,1);

commonJS There are three types of module definitions, module definition (exports), module reference (require) and module label (module)

exports() object Used to export variables or methods of the current module, the only export port. require() is used to introduce external modules. The module object represents the module itself.

Give me a chestnut

// util.jsmodule.exports = {
    getFormatDate:function(date, type){
         if(type === 1){                return &#39;2017-06-15&#39;
          }          if(type === 2){                return &#39;2017 年 6 月 15 日&#39;
          }
    }
}// a-util.jsconst util = require(&#39;util.js&#39;)
module.exports = {
    aGetFormatDate:function(date){
        return util.getFormatDate(date,2)
    }
}

Or the following method

 // foobar.js
 // 定义行为
 function foobar(){
         this.foo = function(){
                 console.log(&#39;Hello foo&#39;);
        }  
         this.bar = function(){
                 console.log(&#39;Hello bar&#39;);
          }
 } // 把 foobar 暴露给其它模块
 exports.foobar = foobar;// main.js//使用文件与模块文件在同一目录var foobar = require(&#39;./foobar&#39;).foobar,
test = new foobar();
test.bar(); // &#39;Hello bar&#39;

5 总结

CommonJS 则采用了服务器优先的策略,使用同步方式加载模块,而 AMD 采用异步加载的方式。所以如果需要使用异步加载 js 的话建议使用 AMD,而当项目使用了 npm 的情况下建议使用 CommonJS。

相关推荐:

论JavaScript模块化编程

requireJS框架模块化编程实例详解

The above is the detailed content of What is modular programming? Summary of js modular programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools