# 介绍

在 JavaScript 和其他现代前端框架中,“模块方法” 指的是如何通过模块化方式组织和管理代码,以提高代码的可维护性和可复用性。JavaScript 模块可以封装变量、函数、类等逻辑,通过模块导出模块导入机制将这些功能暴露给外部使用。

一个文件就是一个模块

# CommonJS

  • 定义:CommonJS 是 Node.js 中默认使用的模块系统,使用 require 来导入模块,用 module.exports 或 exports 来导出模块。
  • 使用环境:Node.js
  • 使用方法:

导出模块:

const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = {
  add,
  subtract,
};

导入模块:

const math = require("./math");
console.log(math.add(5, 2)); // 输出 7
console.log(math.subtract(5, 2)); // 输出 3

# ES6

  • 定义:ES6(也叫 ES2015)引入了 import 和 export 语法,是现代 JavaScript 模块化的标准。
  • 使用环境:现代浏览器和 Node.js
  • 使用方法:

导出模块:

export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

导入模块:

import { add, subtract } from "./math.js";
console.log(add(5, 2)); // 输出 7
console.log(subtract(5, 2)); // 输出 3

默认导出:

const square = (x) => x * x;
export default square;

默认导入:

import square from "./utils.js";
console.log(square(3)); // 输出 9

# AMD

  • 定义:AMD (Asynchronous Module Definition) 模块系统主要用于浏览器环境,适合异步加载模块。require.js 是一个流行的 AMD 实现。
  • 使用环境:浏览器
  • 使用方法:

定义和导出模块:

define([], function () {
  return {
    add: function (a, b) {
      return a + b;
    },
    subtract: function (a, b) {
      return a - b;
    },
  };
});

导入模块:

require(["math"], function (math) {
  console.log(math.add(5, 2)); // 输出 7
});

# UMD

  • 定义:UMD (Universal Module Definition) 是一种兼容多种模块加载器的模块系统,通常用于构建兼容性较好的库。
  • 使用环境:浏览器、Node.js、AMD 模块系统等
  • 使用方法:
(function (root, factory) {
  if (typeof define === "function" && define.amd) {
    define([], factory);
  } else if (typeof module === "object" && module.exports) {
    module.exports = factory();
  } else {
    root.myModule = factory();
  }
})(this, function () {
  return {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
  };
});

# IIFE

  • 定义:在模块化标准出现之前,IIFE (Immediately Invoked Function Expression) 是一种常见的模块模式。它通过函数立即执行来创建作用域并封装变量。
  • 使用环境:
  • 使用方法:
const myModule = (function () {
  const privateVar = "I am private";
  function privateMethod() {
    console.log(privateVar);
  }
  return {
    publicMethod: function () {
      privateMethod();
    },
  };
})();
myModule.publicMethod(); // 输出 'I am private'