何时使用“import * as Foo"与“导入 Foo"? [英] When to use "import * as Foo" versus "import Foo"?

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

问题描述

我正在使用 BabelJS 将 BackboneJS (v1.2.2) 项目转换为 ES6.

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

我注意到两者之间存在差异:

I noted that there's a difference between:

import Backbone from 'backbone'

import * as Backbone from 'backbone'

阅读这里后我明白前者是导入Backbone的默认导出后者允许我导入整个模块并通过属性符号引用其命名导出."

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天全站免登陆