【问题标题】:Undertanding import in ES6理解 ES6 中的导入
【发布时间】:2017-10-10 00:08:28
【问题描述】:

我遇到了这个源代码。 第一行看不懂:

import type { a, b, c, d } from 'types'

有什么区别

import { a, b, c, d } from 'types' 你能解释一下吗?谢谢

import type { a, b, c, d } from 'types'// not sure what it does
import { a, b, c, d } from 'types' // I am familar with this

【问题讨论】:

  • type这个词后面有逗号吗?
  • 不,没有逗号,代码按预期工作,缺少逗号实际上让我感到困惑
  • 代码使用flowtype
  • 是的@Radex 是正确的,它应该使用flowtype。

标签: javascript ecmascript-6 flowtype


【解决方案1】:

这不是普通的 JavaScript import 用法。这可能是 Flow,或一种密切相关的转译语言。

我从 Flow 项目中找到了一篇名为 Announcing Import Type 的博文。我不知道 Flow,但它看起来像是 JavaScript 的严格类型超集。 import type 语句是在不导入类本身的情况下导入类的类型信息的方式。他们给出了一个示例,您可能希望在函数中声明混合类型的形式参数并需要导入适当的类型:

import type {Crayon, Marker} from 'WritingUtensils';
module.exports = function junkDrawer(x: Crayon, y: Marker): void {}

【讨论】:

    【解决方案2】:

    它正在从文件中导入类型定义。

    // Here you are importing the actual method, variable from the file.
    import xyz from 'abc';`
    
    // Here you are importing the type defination of xyz
    import type { xyz } from 'abc';
    

    现在如果你想把它用作

    let a: xyz = new xyz();

    【讨论】:

      【解决方案3】:

      来自 MDN,虽然 OP 中缺少的昏迷很奇怪:

      导入默认值:可以有默认导出(无论是 是一个对象、一个函数、一个类等)。进口声明可以 然后用于导入此类默认值。

      最简单的版本直接导入默认:

      import myDefault from '/modules/my-module.js';

      也可以 使用上面看到的默认语法(命名空间导入或 命名进口)。在这种情况下,默认导入必须是 先声明。例如:

      import myDefault, {foo, bar} from '/modules/my-module.js'; // specific, named imports

      换句话说,这会将默认值导入为 myDefault,然后导入命名的导出。

      【讨论】:

        猜你喜欢
        • 2019-04-07
        • 2023-03-11
        • 2016-10-29
        • 1970-01-01
        • 2016-06-22
        • 1970-01-01
        • 1970-01-01
        • 2016-02-05
        相关资源
        最近更新 更多