伟大的 gugly muglys!这比它需要的更难。
导出一个平面默认值
这是使用一个很好的机会传播(...在{ ...Matters, ...Contacts }下面:
// imports/collections/Matters.js
export default {           // default export
  hello: 'World',
  something: 'important',
};
// imports/collections/Contacts.js
export default {           // default export
  hello: 'Moon',
  email: 'hello@example.com',
};
// imports/collections/index.js
import Matters from './Matters';      // import default export as var 'Matters'
import Contacts from './Contacts';
export default {  // default export
  ...Matters,     // spread Matters, overwriting previous properties
  ...Contacts,    // spread Contacts, overwriting previosu properties
};
// imports/test.js
import collections from './collections';  // import default export as 'collections'
console.log(collections);
然后,从命令行(从项目根目录 /)运行 babel 编译的代码:
$ npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node 
(trimmed)
$ npx babel-node --presets @babel/preset-env imports/test.js 
{ hello: 'Moon',
  something: 'important',
  email: 'hello@example.com' }
导出一棵树状默认值
如果您不想覆盖属性,请更改:
// imports/collections/index.js
import Matters from './Matters';     // import default as 'Matters'
import Contacts from './Contacts';
export default {   // export default
  Matters,
  Contacts,
};
输出将是:
$ npx babel-node --presets @babel/preset-env imports/test.js
{ Matters: { hello: 'World', something: 'important' },
  Contacts: { hello: 'Moon', email: 'hello@example.com' } }
导出多个命名导出,无默认值
如果您专注于DRY,则导入的语法也会发生变化:
// imports/collections/index.js
// export default as named export 'Matters'
export { default as Matters } from './Matters';  
export { default as Contacts } from './Contacts'; 
这将创建 2 个没有默认导出的命名导出。然后改变:
// imports/test.js
import { Matters, Contacts } from './collections';
console.log(Matters, Contacts);
和输出: 
$ npx babel-node --presets @babel/preset-env imports/test.js
{ hello: 'World', something: 'important' } { hello: 'Moon', email: 'hello@example.com' }
导入所有命名的导出
// imports/collections/index.js
// export default as named export 'Matters'
export { default as Matters } from './Matters';
export { default as Contacts } from './Contacts';
// imports/test.js
// Import all named exports as 'collections'
import * as collections from './collections';
console.log(collections);  // interesting output
console.log(collections.Matters, collections.Contacts);
请注意上一个示例中的解构 import { Matters, Contacts } from './collections';。
$ npx babel-node --presets @babel/preset-env imports/test.js
{ Matters: [Getter], Contacts: [Getter] }
{ hello: 'World', something: 'important' } { hello: 'Moon', email: 'hello@example.com' }
在实践中
鉴于这些源文件:
/myLib/thingA.js
/myLib/thingB.js
/myLib/thingC.js
创建一个/myLib/index.js来捆绑所有文件违背了导入/导出的目的。首先将所有内容设为全局性比通过 index.js“包装文件”导入/导出使所有内容全局化要容易得多。
如果你想要一个特定的文件,import thingA from './myLib/thingA';在你自己的项目中。
仅当您为 npm 或多年多团队项目打包时,为module创建带有导出的“包装文件”才有意义。
走到这一步了吗?有关更多详细信息,请参阅文档。
另外,是的,Stackoverflow 终于支持三个`s 作为代码围栏标记。