SoFunction
Updated on 2025-03-06

About what is javascript modularity and why it is used for modular development

Modularity is a design model for software development. It divides a large software system into multiple independent modules, each with its own functions and interfaces and can work independently from other modules.

Let’s first make a eight-part article

Modular development can bring the following benefits:

  • Improve code reusability: Modularity can divide the code into reusable parts, reduce the redundancy and repetition of the code, and improve code reusability.
  • Simplify code maintenance and debugging: When a software system becomes more and more complex, modular development can make each module relatively independent, so that each module can be easily maintained and debugged without taking into account the complexity of the entire system.
  • Improve the readability of the code: Modularity can make the code more structured, clear and clear, thereby improving the readability and maintainability of the code.
  • Improve development efficiency: Modular development allows team members to develop in parallel on different modules, thereby improving development efficiency.
  • Reduce the risk of the project: Modular development can make developers pay more attention to the interfaces and dependencies between modules, thereby reducing the risk of the project.

In short, modular development is an effective software development model that can improve the quality, efficiency and maintainability of software development. Especially in the development of large software systems, modularization is even more indispensable.

How to use it in actual work

Scene 1:In the Ajax requests for the front and back end interaction, different requests are classified. Each type of business is placed in a module, including user-related, product list-related, and order-related. In order to make the business logic clearer, when changing the relevant code, you only need to find the corresponding file, modify the user-related, modify the product-related, etc. Is it much clearer, is it much easier to use?

Let's take a look at the example

import axios from '../utils/request'
import md5 from 'md5'
 
// Log inexport const login = async (params)=>{
  let {data} = await ('users/login',{params})
  if(){
    //Storage tokens in browser cache    ('token',)
  }
  return data
}
// Change passwordexport const resetPwd = async (params)=>{
  // Encrypt the password  let {data} = await ('users/resetPwd',params)
  return data
}
//...other business

Example,

export const getDetail = async (id)=> {
  let {data} =  (`/goods/detail/${id}`);
  return data
}
 
export const getCategory = async () =>{
  let {data} =  ('/categories');
  return data
}
 
export const search = (params) =>{
  let {data} =  ('/search', { params });
  return data
}

Each js (module) has its own relevant code, and the codes do not affect each other.

As shown in the following code, all requests are placed in a file, regardless of module

import axios from '../utils/request'
import md5 from 'md5'
 
// Log inexport const login = async (params)=>{
  let {data} = await ('users/login',{params})
  if(){
    //Storage tokens in browser cache    ('token',)
  }
  return data
}
//Inquiry of productsexport const search = (params) =>{
  let {data} =  ('/search', { params });
  return data
}
 
// Change passwordexport const resetPwd = async (params)=>{
  // Encrypt the password  let {data} = await ('users/resetPwd',params)
  return data
}
//Product detailsexport const getDetail = async (id)=> {
  let {data} =  (`/goods/detail/${id}`);
  return data
}
//Get product categoriesexport const getCategory = async () =>{
  let {data} =  ('/categories');
  return data
}
 
//...other business

Isn't it very messy? This is just a little bit of business. If the larger business system has hundreds of interfaces, if it cannot be divided according to the module, the code will be a shit mountain. There will be problems with multiple people's collaboration, and there is no way to start the code maintenance.

Scene 2:Everyone knows a single page application, and its biggest advantage is that it does not have to switch pages, which is excellent for user experience. For example, the common pages of vue are that the head, tail and menus are not moved, and only the content area is moving. A piece of old is deducted in the dom and a new one is replaced. In this way, each piece should exist independently, which is the common .vue file. Use webpack to convert the .vue file into a .js file. This js is a modular file. The page and name are associated through routing. Deducting and replacing new ones require a route to complete the process.

To sum up, modularity is actually classified.

Several modular syntaxes are attached

No matter which syntax, it is just a fixed way of writing. Focus on understanding two concepts: one export (expose the current module) and the other import (using which module)

1. CommonJS

CommonJS is a modular specification for server-side JavaScript, using require and export and import modules. For example:

// 
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const hello = () => 'Hello, Qianfeng';
 
 = {
  add,
  subtract,
  hello
};
 
// 
const math = require('./math');
 
((2, 3)); // Output 5((3, 2)); // Output 1(); // Output Thousand Fronts,Hello

2. AMD

AMD (Asynchronous Module Definition, asynchronous module definition) is a modular specification for browser-side JavaScript. It uses define to define modules and loads modules asynchronously through require. For example:

// //defineThe first parameter indicates the module that the current module depends on,Can be an array of strings,It can also be a function// Define a name "math" Modules,Depend on "jquery" and "underscore" Two modulesdefine(['jquery', 'underscore'], function($, _) {  // Define the function of the module  const add = function(a, b) {    return a + b;  };  const multiply = function(a, b) {    return a * b;  };  const test = ()=>{    var arr = ['foo', 'bar', 'qfedu'];    var arrUpper = _.map(arr, function(str) {      return ();    });    return  arrUpper;  }    // Functions of exporting modules  return {    add: add,    multiply: multiply,    test:test  };});// (['./math'], function(math) {  ((2, 3)); // Output 5  ((3, 2)); // Output 1  (())//Output ["FOO", "BAR", "QFEDU"]});

3. ES6 module

ES6 modules are the official modular specification of JavaScript, using import and export modules to import and export. For example:

// 
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
 
// 
import { add, subtract } from './math';
 
(add(2, 3)); // Output 5(subtract(3, 2)); // Output 1

4. UMD

UMD (Universal Module Definition) is a general modular solution that supports multiple modular specifications. It supports both CommonJS, AMD and global variables. For example:

(function (root, factory) {
  if (typeof define === 'function' && ) {
    define(['exports'], factory);
  } else if (typeof module === 'object' && ) {
    factory();
  } else {
    factory(( = {}));
  }
}(typeof self !== 'undefined' ? self : this, function (exports) {
  const add = (a, b) => a + b;
  const subtract = (a, b) => a - b;
 
   = add;
   = subtract;
}));

This is the article about what JavaScript modularity is and why it is developed using modularity. For more related content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!