简体   繁体   English

ES6中的导入功能

[英]Undertanding import in ES6

I came across this source code. 我遇到了这个源代码。 I do not understand the first line: 我不明白第一行:

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

What is the difference with 有什么区别

import { a, b, c, d } from 'types' Could you please explain? import { a, b, c, d } from 'types'您能解释一下吗? Thanks 谢谢

 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 

This is not vanilla JavaScript import usage. 这不是普通的JavaScript import用法。 This is probably Flow, or a closely-related transpiled language. 这可能是Flow,或紧密相关的翻译语言。

I found a blog post from the Flow project entitled Announcing Import Type . 我在Flow项目中找到了一篇博客文章,名为“ 宣布导入类型” I don't know Flow, but it looks like a strictly-type superset of JavaScript. 我不知道Flow,但它看起来像JavaScript的严格类型超集。 The import type statement is how you import type information about a class without importing the class itself. import type语句是您如何导入有关类的类型信息而不导入类本身的方式。 They give an example where you might want to declare stirctly-typed formal arguments in a function and need to import the appropriate types: 它们给出了一个示例,您可能想在函数中声明混合类型的形式形参,并需要导入适当的类型:

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

It is importing type definitions from the file. 它正在从文件导入类型定义。

// 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';

Now if you want to use it as 现在,如果您想将其用作

let a: xyz = new xyz();

From MDN, although the missing comas from OP is weird: 从MDN,尽管OP中缺少的昏迷很奇怪:

Importing defaults: It is possible to have a default export (whether it is an object, a function, a class, etc.). 导入默认值:可以进行默认导出(无论是对象,函数,类等)。 The import statement may then be used to import such defaults. 然后,可以使用import语句导入此类默认值。

The simplest version directly imports the default: 最简单的版本直接导入默认值:

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

It is also possible to use the default syntax with the ones seen above (namespace imports or named imports). 也可以将默认语法与上面提到的语法一起使用(命名空间导入或命名导入)。 In such cases, the default import will have to be declared first. 在这种情况下,必须先声明默认导入。 For instance: 例如:

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

In other words, this will import the default as myDefault, and then import the named exports. 换句话说,这会将默认值导入为myDefault,然后导入命名的导出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM