在ES6中组合多个导入结构

时间:2017-12-01 12:39:39

标签: javascript reactjs import ecmascript-6

在我的应用程序中,我经常import React.js作为此

import * as React from 'react'

但是有一些类,我大量使用一些嵌套的对象/或嵌套对象的方法,如React.Children.toArray

我希望尽可能地消除重复,因此希望从Children模块或更好react导入Children.toArray,但仍需要导入所有React为了让JSX工作。

有没有像这种伪代码的方式:

import * as React, {Children: {toArray}} from 'react'

规范表明它不可能: http://www.ecma-international.org/ecma-262/6.0/#sec-imports

  

ImportClause:

     

...

     

ImportedDefaultBinding,NameSpaceImport

     

ImportedDefaultBinding,   NamedImports

2 个答案:

答案 0 :(得分:1)

我认为这是你能做的最好的事情。

import React, {Children} from 'react';

const {toArray} = Children;

答案 1 :(得分:0)

命名导入不能被破坏,它看起来与结构模式相同,但事实并非如此。

您可能会获得error

  

ES2015命名的进口不会破坏。使用另一个声明   进口后解构。

这让我们可以选择:

import foo, { bar } from 'module';

const { nested } = bar;