Assign array to a variable before exporting as module default
原因:错误的写法,解决

  1. 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帮我补上了上下文

  1. // const.js
  2. export default {
  3. test1: 1,
  4. test2: 2
  5. }
  6. // use.js
  7. import { test1,test2 } from './const.js';
  8. console.log('test1:',test1); // undefined
  9. console.log('test2:',test2); // undefined

原因就在于:

  1. 对象解构的语法和 命名导出的语法长得一模一样,虽然语法一模一样,
  2. 但是由于两者使用的上下文不一样(this),
  3. import {a,b, c } from ‘./xxx’,这种情况下就是命名导出,不和import/export一起使用时才是对象解构
    1. babel 发现了babel5的这个问题,
    2. babel6中已经进行了修复。上述代码在babel6中打印的结果就是undefined,undefined
    3. 为了友好的过度,目前阶段,只是采用警告的方式来提醒用户

export default {}正确的写法

  1. // const.js
  2. const test1 = 1
  3. const test2 = 2
  4. export default {
  5. test1,
  6. test2
  7. }
  8. // 或者,推荐这种语法
  9. export const test1 = 1
  10. export const test2 = 2
  11. export { default as Customers} from "./customers/reducer"

import导入

  1. // use.js
  2. import * as lib from './const.js';
  3. console.log(lib.a);
  4. console.log(lib.b);
  5. import { test1,test2 } from './const.js';
  6. console.log('test1:',test1);
  7. console.log('test2:',test2);

既然有插件支持了,我们为什么不能一直用错误用法1呢?

  1. 这比正确用法的写法简洁很多。

原因就是如果要使用插件,就必须要使用babel将esm转换为cjs,
导致后面的打包工具难以对代码进行静态分析了。没有了静态分析,就没法做tree shaking了

esm规范

  1. // 导出方式
  2. export default 'hello world'; // default export
  3. export const name = 'yj'; // named export
  4. // 导入方式
  5. import lib from './lib'; // default import
  6. import * as lib from './lib'; //
  7. import { method1, method2 } from './lib';