• 模块化之CJS, AMD, UMD 和 ESM


    [[toc]]

    模块化优点

    • 防止命名冲突
    • 代码复用
    • 高维护性

    CJS, AMD, UMD 和 ESM

    历史

    • ES6之前,JS一直没有自己的模块体系
    • 后来社区出现了CommonJS和AMD,
    • CommonJS 主要用于服务器(Node)
    • AMD 主要用于浏览器
    • ES6引入了ESM
    • 到此,JS终于有了自己的模块体系,基本上可以完全取代CJS和AMD

    服务端:

    • 同步加载模块
    • CommonJS => NodeJS、Browserify

    客户端

    • 异步加载模块
    • AMD => requireJS
    • CMD => seaJS

    Snipaste_2023-08-13_12-20-15

    CJS:server

    • CJS 是 CommonJS 的缩写。
    • 针对环境: 服务器端,2009年,Node 就是使用 CJS 模块
    • 如何识别: module.exportsrequire()

    特点:

    • CJS 不能在浏览器中工作,它必须经过转换和打包,Browserify 工具,我们可以在浏览器端使用采用CommonJS规范的js文件
    • 运行: 同步导入模块
    • 加载: 动态,被加载的时候运行
    • 输出: 值的浅拷贝
    • CJS 模块加载 ESM 模块: 不能使用require命令,而要使用import()函数
    // 1. CJS 基本使用
    // 定义模块
    const obj = {
       a: 1};
    module.exports = obj;
    // 使用模块
    const obj = require('./test.js');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    // 2. CJS 输出值拷贝
    /*************** a.js**********************/
    let count = 0
    exports.count = count; // 输出值的拷贝
    exports.add = ()=>{
       
        //这里改变count值,并不会将module.exports对象的count属性值改变
        count++;
    }
    /*************** b.js**********************/
    const {
        count, add } = require('./a.js')
    console.log(count) //0
    add();
    console.log(count)//0
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    AMD:client

    • 英文名: Asynchronous Module Definition
    • 中文名: 异步模块化定义方案
    • 针对环境: web浏览器,异步适合浏览器
    • 项目目标: JavaScript生态的模块化解决方案
    • 如何识别: define(id?, dependencies?, factory) + require
  • 相关阅读:
    yakit使用爆破编码明文_dnslog使用
    【Web漏洞探索】文件上传漏洞
    SQL学习二十、SQL高级特性
    js数据类型和判断数据类型的方法
    【Git】Git 的基本操作 -- 详解
    《机器学习——数学公式推导合集》1. 最小二乘法(least square method)求解线性模型
    apache maven安装教程
    Windows平台安装GDB调试器
    idea不能设置包名为con
    (41)STM32——外部SRAM实验笔记
  • 原文地址:https://blog.csdn.net/qubes/article/details/134272202