繁体   English   中英

ES6导入/导出与CommonJS导出/需求如何配合

[英]How does ES6 import / export play along with CommonJS exports / require

有时您想结合使用这些语法,最常见的是在import使用commonjs语法的内容时。 例如,某些情况已在此处讨论:

如何正确地将ES6“导出默认值”与CommonJS“要求”一起使用?

但是肯定还会发生更多情况!

正如@Bergi和@Mike在评论中指出的那样,如何处理ES6导入/导出取决于转译器(最常见的是Babel)。 很少有示例,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}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM