模块化

71 阅读1分钟

CommonJS

原理

// require函数的伪代码
function require(path){
  if(该模块有缓存吗){
    return 缓存结果;
  }
  function _run(exports, require, module, __filename, __dirname){
    // 模块代码会放到这里
    // 模块代码会放到这里
  }
  
  var module = {
    exports: {}
  }
  
  _run.call(
    module.exports, 
    module.exports, 
    require, 
    module, 
    模块路径, 
    模块所在目录
  );
  
  // 把 module.exports 加入到缓存;
  return module.exports;
}

例子: 求m的值

// 1.js
exports.a = 'a';
module.exports.b = 'b';
this.c = 'c';
module.exports = {
  d: 'd',
};

// 引入1.js
const m = require('./1.js');
console.log(m); // {d:'d'}
// 1.js
exports.a = 'a';
module.exports.b = 'b';
this.c = 'c';

// 引入1.js
const m = require('./1.js');
console.log(m); // {a: 'a', b: 'b', c: 'c'}

ES Module

符号绑定

let a = 1
let b = a
a = 2
console.log(b) // 1 

./counter.js

var count = 1;

export { count };

export function increase() {
    count++;
}

引入./counter.js

import { count as c, increase } from './counter.js';

console.log(c); // 1
increase();
console.log(c); // 2

引入./counter.js

import { count, increase } from './counter.js';
import * as counter from './counter.js';

// 相当于: const c = counter.c
const { count: c } = counter;
increase();
console.log(count);// 2
console.log(counter.count);// 2
console.log(c);// 1

commonJS 和 esModule 区别

  • CMJ是社区标准, es module 是官方标准
  • CMJ只能在node中执行, es module 各种环境均可
  • CMJ通过函数的方式实现模块化, ESM 通过新语法实现模块化
  • 动态静态倒入
    • CMJ动态依赖, 同步执行. const a = require('./1.js')
    • ESM 既支持动态倒入, 异步, import('./1.js').then()
    • ESM 又支持静态倒入, import antd from 'antd'