ES Module 和 Commonjs 的区别
1. 语法
1.1 ES Module
导出:export / export default
导入: import * from 'module'
1.2 Commonjs
导出:module.exports
导入:const module = require('module')
2. 特性
2.1 ES Module
静态引入、编译时引入(支持Tree shaking)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // lib.mjs 2 export let a = 1 3 export const b = 2 4 export function aPlus1 () { 5 return a++ 6 }
// index.mjs import { a, aPlus1 } from './lib.mjs' console.log(a) // 1 aPlus1() console.log(a) // 2
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// package.json - 新版本node支持执行ES Mdolue,不过要加上这个配置,且文件后缀要为mjs { "type": "module" }
2.2 Commonjs
动态引入、执行时引入
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// lib.js let a = 1 let b = 2 function aPlus1 () { return a++ } module.exports = { a, b, aPlus1 }
// index.js let { a, aPlus1 } = require ('./lib.js') console.log(a) // 1 aPlus1() console.log(a) // 1