JS 模块化

102 阅读2分钟

一、简介

1、作用

  • 避免命名冲突
  • 更好的分离,按需载入
  • 更好的可维护性
  • 更高的复用性

2、主流

  • CommonJS
    • 主要用于服务端
    • 输出的值是浅拷贝,输出后原模块内部发生变化不影响值,静态
  • ES6 Module
    • 主要用于浏览器端
    • 先生成引用,执行时再加载,原模块内部发生变化会跟着变化,动态

3、其他

  • AMD
    • 声明时加载
  • CMD
    • 懒加载和按需加载
  • 都是用于解决浏览器异步加载

模块化发展史 英语不好的小伙伴打开网站翻译功能体验更佳

二、ES6 Module

1、命名导出

  • 导出
// module.js
// 方式一:
export const xxx1 = 111
// 方式二:
const xxx2 = 222
export {xxx2}
  • 按需导入
// main.js
import {xxx1,xxx2} from './module.mjs'
console.log(xxx1,xxx2); // 111,222
  • 全部导入
// main.js
import * as xxx from './module.mjs'
console.log(xxx.xxx1);

2、默认导出

  • 导出
    • 只能有一个默认导出
// module.js
const xxx1 = 111
export default xxx1
  • 导入
    • xxx可以另起别名
// main.js
import xxx from './module.mjs'
console.log(xxx); // 111

3、别名导入/导出

3.1、别名导出

  • 导出
// main.js
const xxx1 = 111
export {xxx1 as new_name}
  • 导入
// main.js
import {new_name} from './module.mjs'
console.log(new_name); // 111

3.2、别名导入

  • 导出
// main.js
export const xxx1 = 111
  • 导入-别名
// main.js
import {xxx1 as new_name} from './module.mjs'
console.log(new_name); // 111

4、复合写法

  • 导出
export const xxx1 = 111
const xxx2 = 222
export default xxx2
  • 导入
import xxx2,{xxx1} from './module.mjs'
console.log(xxx1,xxx2);

5、拓展

注意:默认导出的是值

  • 命名导出的是引用

验证过程

  • 导出
// 默认导出
let a = 1
export default a
setTimeout(() => {
    a='我变了'
}, 500);
// 命名导出
let b = 1
setTimeout(() => {
    b = '我变了'
}, 500);
export {b}
  • 导入
import  a,{b} from './module.mjs'

// 默认导出
console.log('默认导出:',a); // 默认导出: 1
setTimeout(() => {
    console.log('默认导出:',a); // 默认导出: 1
}, 1000);

// 命名导出
console.log('命名导出:',b); // 命名导出: 1
setTimeout(() => {
    console.log('命名导出:',b); // 命名导出: 我变了
}, 1000);