伟大的大嘴猫!这比它需要的更难。
导出一个平面默认值
这是使用价差...
的绝佳机会({ ...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 或多年多团队项目打包时,为模块创建带有导出的“包装文件”才有意义。
做到这一步了吗?有关更多详细信息,请参阅文档。
此外,Stackoverflow 终于支持三个 `s 作为代码围栏标记了。