ES6导入/导出如何与CommonJS exports / require一起发挥作用

时间:2016-04-19 14:12:20

标签: javascript module ecmascript-6 commonjs

有时你想要结合这些语法,最常见的是import使用commonjs语法的东西。有些案例已在此处讨论过:

How to correctly use ES6 "export default" with CommonJS "require"?

但肯定会发生更多情况!

1 个答案:

答案 0 :(得分:-1)

正如@Bergi和@Mike在评论中所指出的,它取决于转换器(最常见的是Babel),它如何应对ES6导入/导出。很少的例子,你用Babel(用它的标准插件)得到的东西:

CommonJS导出,ES6导入

module.exports = 1    // a.js
import one from './a' // b.js
// one === 1

module.exports = {one: 1}  // a.js
import obj from './a'      // b.js
// obj is {one: 1}

import * as obj from './a' // b.js
// obj.one === 1 ; however, check out the 'funky stuff' below

import {one} from './a'    // b.js
// one === 1

ES6导出,CommonJS需要

export default 1 // a.js
const one = require('./a').default
// one === 1

export const one = 1
const one = require('./a').one
// one === 1

时髦的东西

module.exports = 1          // a.js
import * as obj from './a'  // b.js
// obj is {default: 1}

module.exports = {one: 1}   // a.js
import * as obj from './a'  // b.js
// obj is {one: 1, default: {one: 1}}