【问题标题】:"export default from" doesn't work with Babel React“export default from” 不适用于 Babel React
【发布时间】:2017-04-23 00:53:45
【问题描述】:

我使用react 来构建我的组件库。我需要有一个index.js 才能在一个地方导入所有组件。

类似这样的:

MyComponents/
  Button.js
  Label.js
  index.js

index.js里面我接下来尝试做:

// this export nothing
export {default} from './Button';
// this tells me about syntax error
export default from './Button';

我发现只有这个解决方案有效

import Button from './Button';
export default Button;

但我发现一些 React 组件库使用了我上面提到的语法 (export default from './Button') - 它以某种方式工作。看起来他们使用了一些 babel-plugin-transform-* 来执行此操作。

请找我了解如何将我的两行导入导出转换为export ... from ... 的一行。谢谢。

附:最后我需要这样做:import Button from './MyComponents';

【问题讨论】:

  • 请尝试export {default as Button} from './Button'
  • 遗憾的是它不起作用。它可以编译,但不允许从模块中导入 Button。
  • 我复制了你的例子,export default from './Button' 为我工作。编译并正确显示。我使用以下 Babel 预设:"es2015", "stage-0", "react"。你能告诉我你的 Babel/Webpack 配置吗? See a screenshot here
  • 嗨。我不使用stage-0stage-1,因为这是一个实验性功能。这可能是一个原因。
  • 哦,是的。最后我在这里找到了这个提案的描述:github.com/leebyron/ecmascript-export-default-from

标签: javascript node.js reactjs npm babeljs


【解决方案1】:

使用以下语法:

File: layouts/index.js

export {default as Flex} from './flex'
export {default as Grid} from './grid'
export {default as Dock} from './dock'

然后就可以使用了

import { Dock, Grid } from 'layouts'

import layouts from 'layouts'

<layouts.Flex >...</layouts.Flex>

为了导出上述方法创建的嵌套索引,您可以使用export * 语法:

File: icons/index.js

export * as action from './action';
export * as alert from './alert';
export * as av from './av';

用法:

import * as icons from 'material/icons'

<icons.action.Close />

【讨论】:

  • 抱歉,我需要使用import Button from './MyComponents'; 而不是import {Button} from './MyComponents';
  • 加上星号也不起作用 - SyntaxError: export * as Button from './Button';
  • 如果您只想导入按钮,您可以随时import Button from './MyComponents/Button',这样在语义上更正确。
  • 你说得对,export * 在这种情况下不起作用。它仅适用于上述语法导出的嵌套索引。我要编辑答案。
  • 我的项目结构具有更大的层次结构。这是我非常简化的示例,用于了解如何正确使用 index.js 文件中的导入来使用每个组件的目录。
【解决方案2】:

要使用这种结构:

export default from './Button';

我们需要使用preset-stage-1

如何使用

  1. npm install babel-preset-stage-1 --save-dev
  2. 编辑文件package.json 并将stage-1 添加到babel 中的presets 部分。

package.json 的示例

"babel": {
  "presets": [
    "es2015",
    "stage-1",
    "react"
  ]
},

更多信息

这是对 ECMAScript 的提议 - https://github.com/leebyron/ecmascript-export-default-from(仍在审核中)

【讨论】:

    【解决方案3】:

    只需使用export * from "./Button"; 即可导出整个模块。这将有助于您的用例。

    不幸的是,没有单行语法可以只导出另一个模块的默认值。

    【讨论】:

    • 在 Button.js 中,我使用这个导出:export default Button;,从我的描述中可以看出 - 我可以导入和导出。但问题是如何仅在一个字符串中执行此操作。
    • 尝试从“./Button”导出*;这将导出所有内容以及默认值。没有解决方案只在一行中导出默认值。希望这可以帮助。我更新了我的答案
    • 看来你完全不明白我的问题。并且import Button from './Button';在我原来的问题中提到过,如果你仔细阅读的话。
    • 我理解你的问题,没有可用的解决方案仅导出“一行”中另一个模块的默认导入。但你可以从“./Button”导出*;这将完美地工作
    猜你喜欢
    • 2019-03-05
    • 2019-08-04
    • 2019-08-19
    • 2020-09-16
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多