Skip to content

JS 模块规范化 简化版笔记

CommonJS 规范

服务端应用广泛

创建代码

js
const name = "尚硅谷";
const slogan = "让天下没有难学的技术!";

function getTel() {
  return "010-56253825";
}

function getCities() {
  return ["北京", "上海", "深圳", "成都", "武汉", "西安"];
}

// 通过给exports对象添加属性的方式,来导出数据(注意:此处没有导出getCities)
exports.name = name;
exports.slogan = slogan;
exports.getTel = getTel;
js
const name = "张三";
const motto = "相信明天会更好!";

function getTel() {
  return "13877889900";
}

function getHobby() {
  return ["抽烟", "喝酒", "烫头"];
}

// 通过给exports对象添加属性的方式,来导出数据(注意:此处没有导出getHobby)
exports.name = name;
exports.slogan = slogan;
exports.getTel = getTel;
js
// 引入school模块暴露的所有内容
const school = require("./school");

// 引入student模块暴露的所有内容
const student = require("./student");

导出数据

在 CommonJS 标准中,导出数据有两种方式:

  1. 第一种方式:module.exports = value
  2. 第二种方式:exports.name = value

导入数据

在 CJS 模块化标准中,使用内置的 require 函数进行导入数据

js
// 直接引入模块
const school = require("./school");

// 引入同时解构出要用的数据
const { name, slogan, getTel } = require("./school");

// 引入同时解构+重命名
const { name: stuName, motto, getTel: stuTel } = require("./student");

ES6 模块规范

浏览器端应用广泛

创建代码

js
// 导出name
export let name = { str: "尚硅谷" };
// 导出slogan
export const slogan = "让天下没有难学的技术!";

// 导出name
export function getTel() {
  return "010-56253825";
}

function getCities() {
  return ["北京", "上海", "深圳", "成都", "武汉", "西安"];
}
js
// 导出name
export const name = "张三";
// 导出motto
export const motto = "相信明天会更好!";

// 导出getTel
export function getTel() {
  return "13877889900";
}

function getHobby() {
  return ["抽烟", "喝酒", "烫头"];
}
js
<script type="module" src="./index.js"></script>

导出数据

  1. 分别导出(上方使用的就是分别导出)
  2. 统一导出
  3. 默认导出
js
// 导出name
export let name = { str: "尚硅谷" };
// 导出slogan
export const slogan = "让天下没有难学的技术!";

// 导出getTel
export function getTel() {
  return "010-56253825";
}
js
const name = { str: "尚硅谷" };
const slogan = "让天下没有难学的技术!";

function getTel() {
  return "010-56253825";
}

function getCities() {
  return ["北京", "上海", "深圳", "成都", "武汉", "西安"];
}

// 统一导出了:name,slogan,getTel
export { name, slogan, getTel };
js
const name = "张三";
const motto = "走自己的路,让别人五路可走!";

function getTel() {
  return "13877889900";
}

function getHobby() {
  return ["抽烟", "喝酒", "烫头"];
}

//默认导出:name,motto,getTel
export default { name, motto, getTel };

导入数据

对于 ES6 模块化来说,使用何种导入方式,要根据导出方式决定。

  1. 导入全部
js
// 可以将模块中的所有导出内容整合到一个对象中
import * as school from "./school.js";
  1. 命名导入(分别导出、统一导出)
js
import { name, slogan, getTel } from "./school.js";

// 通过as重命名:
import { name as myName, slogan, getTel } from "./school.js";
  1. 默认导入(默认导出)
js
//默认导出的名字可以修改,不是必须为student
import student from "./student.js";
  1. 命名导入与默认导入混合
js
// 「命名导入」与「默认导入」混合使用,且默认导入的内容必须放在前方:
import getTel, { name, slogan } from "./school.js";
  1. 动态导入(通用)
js
// 允许在运行时按需加载模块,返回值是一个 Promise。
const school = await import("./school.js");
console.log(school);
  1. 直接 import
js
// 例如只是让 mock.js 参与运行
import "./mock.js";