import 语句用于导入从另一个模块导出的绑定
大括号 ({}) 用于导入命名绑定,其背后的概念称为解构赋值。解构赋值的概念是一个过程,可以将数组或对象中的值解压到导入模块中的不同变量中
大括号 ({}) 用于导入命名绑定
我想通过一个例子来解释 ES6 中不同类型的导入
假设我们有一个名为 Animals(Animals.js) 的模块,假设该模块导出默认绑定Man
以及其他几个命名绑定,例如Cat
, Dog
etc
/*
Animals.js
*/
..
export Cat;
export Dog
export default Man
从模块导入单个导出
为了从另一个模块(比如说 Cat)导出单个导出,我们可以这样写
/*
Anothermodule.js
*/
import {Cat} from "./Animals"
对于狗来说也是如此
/*
YetAnothermodule.js
*/
import {Dog} from "./Animals"
从模块导入多个导出
您还可以导入多个模块,如下所示
/*
Anothermodule.js
*/
import {Dog, Cat} from "./Animals"
使用更方便的别名导入导出
/*
Anothermodule.js
*/
import {Dog as Puppy} from './Animals.js';
导入期间重命名多个导出
/*
Anothermodule.js
*/
import {Dog as Puppy, Cat as Kitty} from './Animals.js';
但是在将 Man 导入到另一个模块的情况下,因为它是默认导出,你可以这样写
/*
Anothermodule.js
*/
import Man from './Animals.js';
您还可以混合上述两种变体,例如
/*
Anothermodule.js
*/
import Man, {Dog as Puppy, Cat as Kitty} from '/Animals.js';
导入整个模块的内容
如果你想导入所有你可以使用的东西
/*
Anothermodule.js
*/
import * as Animals from './Animals.js';
在这里,访问导出意味着使用模块名称(在本例中为“Animals”)作为命名空间。例如,如果你想在这种情况下使用 Cat,你可以像下面这样使用它
Animals.Cat
您可以阅读有关导入的更多信息here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
你可以阅读有关解构的内容here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment