ES6 的 import、export 对比 CommonJS 的 require、exports

最近在开发 quickjs-android,一个小型的 JavaScript 引擎封装框架,需要给框架增加模块加载能力,以提高框架的可用度,所以就模块化能力对常用的模块化规范展开分析。

前言

目前常用的模块规范有两种,CommonJS 和 ES6 Module,Node.js 是基于 CommonJS 规范开发的,使用的命令是 require 和 exports。而 ES6 是 JavaScript 的版本标准,2015.06 发版,使用 import 和 export 命令。

CommonJS 和 Node.js

CommonJS 是一种规范,而不是一个框架,可以理解为接口的概念,而 Node.js 是 CommonJS 的一种实现方式,所以 require、exports 并不是 Node.js 独有的方法,任何的框架都可以实现 CommonJS 规范,但是这不是标准的JavaScript规范,所以在浏览器上是无法实现。

ES6

ES6 也是一种 JavaScript 规范,与 CommonJS 不同,全称 ECMAScript 6.0 ,是 JavaScript 版本标准,2015.06 发版。目前已经被多数的浏览器支持,quickjs-android 也支持 ES6,Node.js 在 13.2.0 版本开始也提供了支持。

用法区别

两者的用户很相似,都能够实现导入其它文件模块。

CommonJS

a.js

module.exports.name = 'Hello world';
module.exports.age = 18;

b.js

var a = require('./a.js');
console.log(a.name);
console.log(a.age);
ES6 Module

a.js

export var name = 'Hello world';
export var age = 18;

b.js

import {name, age} from './a.js';
console.log(name);
console.log(age);

区别

CommonJS 模块是运行时调用,就算多次调用 require,对应的模块代码不会重新执行,而是使用之前的结果。而 ES6 是编译时进行,并且不会缓存运行结果,而是动态的去被加载的模块取值,模块里面的变量绑定其所在的模块。

CommonJS
var a = require('./a.js');
a.gender = '男';
var a2 = require('./a.js');
console.log(a2.gender);

输出结果是:男

最后

更多的用法请参考 CommonJS 、 ES6 Module。

你可能感兴趣的:(ES6 的 import、export 对比 CommonJS 的 require、exports)