何时使用“import * as Foo”相对于“进口Foo” [英] When to use "import * as Foo" versus "import Foo"?

查看:283
本文介绍了何时使用“import * as Foo”相对于“进口Foo”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将BackboneJS(v1.2.2)项目转换为ES6 w / BabelJS。

I'm converting a BackboneJS (v1.2.2) project to ES6 w/ BabelJS.

我注意到:

import Backbone from 'backbone'

import * as Backbone from 'backbone'

阅读此处后我明白,前者正在导入Backbone的默认出口,因为后者允许我导入整个模块并通过属性表示法引用其命名的export。

After reading here I understand that the former is importing the default export of Backbone where as the latter allows me to "import the whole module and refer to its named exports via property notation."

我很难理解这些之间的区别。在这两个实例中都会返回对象,但前者似乎是以额外的属性/方法进行装饰。至少我会认为导入整个模块会有更多的属性/方法...但我看到相反。

I'm struggling to understand the difference between these. Objects are returned in both instances, but the former appears to be decorated with additional properties/methods. At the very least I would presume importing "the whole module" would have more properties/methods... but I'm seeing the opposite.

推荐答案

一个模块可以导出单个默认导出和/或一个或多个命名导出。

a module can export a single "default export" and / or one or more named exports.

使用问题中的第一个语法导入只导入默认导出,并在该对象中设置一个命名标识符(Backbone)。

Importing with the first syntax in your question only imports the default export, and sets a named identifier (Backbone in your sample) to that object.

第二种语法称为命名空间导入,它将导入整个模块一个单一的命名空间对象。

The second syntax is known as a namespace import, and it imports the whole module under a single "namespace" object.

例如:

export.js

let b = {b: 2};
export default {a: 1}; // <- this is the ONLY default export
export {b};
export let c = {c: 3};

import.js

import SomeName from 'export'; // 'SomeName' is now the {a: 1} instance.
import {b} from 'export'; // 'b' is now the {b: 2} instance.
import * as ns from 'export'; /* 'ns' now has properties 'default', 'b' & 'c',
  representing {a: 1}, {b: 2} & {c: 3} respectively */

这篇关于何时使用“import * as Foo”相对于“进口Foo”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆