概要
JS主流的导入格式有2种,CommonJS 和 ESModule,从时间上CommonJS出现的较早,很多三方库都使用。ESModule则被现代前端应用所使用,因此主流的做法是让ESModule 适配 CommonJS。
关于esmoduleinterop
两者的区别是 ESModule可以default导出,即module['default']。因此esmoduleinterop要做的就是让CommonJS也有模拟一个default导出,具体看转载。
关于export/require/import
// commjs export
const obj = {
name: "my name"
}
const other = "other"
module.exports = obj
module.exports.other = other
// commonjs require
const commjsExports = require('./commjs')
console.log(commjsExports)
// output
{ name: 'my name', other: 'other' }
// esmodule export
const obj = {
name: "my name"
}
export const other = "other"
export default obj;
// esmodule import
import obj, { other } from './esmodule'
console.log(obj, other)
// output
{ name: 'my name' } other
关于导出对象修改
首先,要明白js的export也是一个js对象,无论那种格式。import obj, { other } from './esmodule' 使用了解构语法,其本质还是js的内置语法,把other从export这个对象中解析了出来。因此,如果模块内修改了导出的对象,都只看import方是值复制还是引用复制。