Assign array to a variable before exporting as module default
原因:错误的写法,解决
- hack做法:// eslint-disable-next-line
不要使用 export default {a, b, c}
不要使用 export default {a, b, c}
不要使用 export default {a, b, c}
深入解析ES Module(一):禁用export default object https://zhuanlan.zhihu.com/p/40733281
export default错误的语法
正确的输出结果应该是 undefined
能够正常输出1,2是因为babel5帮我补上了上下文
// const.js
export default {
test1: 1,
test2: 2
}
// use.js
import { test1,test2 } from './const.js';
console.log('test1:',test1); // undefined
console.log('test2:',test2); // undefined
原因就在于:
- 对象解构的语法和 命名导出的语法长得一模一样,虽然语法一模一样,
- 但是由于两者使用的上下文不一样(this),
- import {a,b, c } from ‘./xxx’,这种情况下就是命名导出,不和import/export一起使用时才是对象解构
- babel 发现了babel5的这个问题,
- babel6中已经进行了修复。上述代码在babel6中打印的结果就是undefined,undefined
- 为了友好的过度,目前阶段,只是采用警告的方式来提醒用户
export default {}正确的写法
// const.js
const test1 = 1
const test2 = 2
export default {
test1,
test2
}
// 或者,推荐这种语法
export const test1 = 1
export const test2 = 2
export { default as Customers} from "./customers/reducer"
import导入
// use.js
import * as lib from './const.js';
console.log(lib.a);
console.log(lib.b);
import { test1,test2 } from './const.js';
console.log('test1:',test1);
console.log('test2:',test2);
既然有插件支持了,我们为什么不能一直用错误用法1呢?
- 这比正确用法的写法简洁很多。
原因就是如果要使用插件,就必须要使用babel将esm转换为cjs,
导致后面的打包工具难以对代码进行静态分析了。没有了静态分析,就没法做tree shaking了
esm规范
// 导出方式
export default 'hello world'; // default export
export const name = 'yj'; // named export
// 导入方式
import lib from './lib'; // default import
import * as lib from './lib'; //
import { method1, method2 } from './lib';