声明: 来源是看到一篇老外写的文章,整理翻译成中文
es6的模块导出大致有导出单个名称、default默认值、还有导出多个list三种形式
三种方式导出、导入大致如下:
// Name Export | Name Import
export const name = 'value'
import { name } from '...'
// Default Export | Default Import
export default 'value'
import anyName from '...'
// Rename Export | NameImport
export { name as newName }
import { newName } from '...'
// Name + Default | Import All
export const name = 'value'
export default 'value'
import * as anyName from '...'
// Export List + Rename | Import List + Rename
export {
name1,
name2 as newName2
}
import {
name1 as newName1,
newName2
} from '...'
以下依次介绍:
a. Name 按名称导出
export const name = 'value';
import { name } from 'some-path/file';
console.log(name); // 'value'
常见错误写法:
❌ What did I say, no name, no export! (就像我说的,没有名称,就不要导出)
export 'value'
import { } // 👈 see I don't even know what to put here...give me a name!
导出时没有定义名称,在导入的时候,都不知道放什么名称
b.Default 默认导出
With a default export, you don’t need any name. Because you can name it whatever you want 👏 (用默认导出,你不需要提供名称,因为你可以自己想怎么定义都行)
export default 'value'
import anyName from 'some-path/file';
console.log(anyName); // 'value'
常见错误:
❌ No Variable Declaration with Default (用默认导出的时候,不需要变量声明)
export default const name = 'value'; // don't try to give me a name!
可以混用 默认导出default + 名称导出name
You can absolutely combine default and name export in one file 🤝 (当然可以在一个文件内上面两种方式混用)
export const name = 'value';
export default 'value'
import anyName, { name } from 'some-path/file';
c. Export List 按组导出
const name1 = 'value1';
const name2 = 'value2';
export {
name1,
name2
}
import {
name1,
name2
} from 'some-path/file'
console.log(
name1, // 'value1'
name2, // 'value2'
)
常见错误:
One important thing to note is that these lists are NOT objects. Yes, I know it looks like it. But it isn’t. I made this confusion when I first learned modules. It’s not an object, it’s an export list! (很重要的一点,这个导出的,并不是一个对象,尽管看起来很像。我第一次接触的时候,也很困惑。但它的确导出的不是一个对象类型,而是一个列表)
// ❌ Export list ≠ Object
export {
name: 'name'
}
重命名导出 Renaming Export
Not happy with the export name. No problem, you can rename it using the as keyword.
const name = 'value'
export {
name as newName
}
import { newName } from 'some-path/file'
console.log(newName); // 'value'
// Original name is not accessible
// 原来的名称,不可用了
console.log(name); // ❌ undefined
❌ Can not combine inline export with export list (不要在按名称导出后又按组导出它)
export const name = 'value';
// You're already exporting name ☝️, don't export me again
export {
name
}
重命名导入 Renaming Import
const name1 = 'value1';
const name2 = 'value2';
export {
name1,
name2 as newName2
}
import {
name1 as newName1,
newName2
} from '...'
console.log(newName1); // 'value1'
console.log(newName2); // 'value2'
❌
name1; // undefined
name2; // undefined
···
## 导入所有 Import All
```js
export const name = 'value';
export default 'defaultValue';
import * as anyName from 'some-path/file';
console.log(anyName.name); // 'value'
console.log(anyName.default); // 'defaultValue'