ES6 Modules 相对于 CommonJS 的优势是什么?

1,901 阅读1分钟

1.CommonJS是一种模块规范,Javascript模块中 并没有一种规范,由此,CommonJS就从民间诞生了

2.ES6 Modules 是继CommonJS之后由官方出的对于模块的一种规范

比较

  1. CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用
  2. CommonJS 模块是运行时加载,ES6 模块是编译时输出接口。
  3. CommonJs 是单个值导出,ES6 Module可以导出多个
  4. CommonJs 是动态语法可以写在判断里,ES6 Module 静态语法只能写在顶层
  5. CommonJs 的 this 是当前模块,ES6 Module的 this 是 undefined

使用

  1. CommonJS 使用require()引入模块
const index = require('./index.js')
  1. ES6 Modules 使用import 引入模块
//index.js 首先要暴露模块
export default index

//main.js中引入模块
import index from './index.js'



//也可以使用分别暴露的方式 暴露多了模块
//index.js
export const index1 = xxxxx
export const index2 = xxxxx

//main.js
import { index1 , index2 } from './index.js'