“export default from” 在使用 Babel React 时无法正常工作。

7

我使用 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' - Przemysław Zalewski
很遗憾它不起作用。它可以编译,但无法从模块中导入按钮。 - Anton Danilchenko
1
我已经复制了你的例子,export default from './Button' 对我来说是有效的。编译并正确显示。我使用以下Babel预设:"es2015", "stage-0", "react"。你能给我展示一下你的Babel/Webpack配置吗?在这里查看截图 - Przemysław Zalewski
嗨。我不使用stage-0stage-1,因为这是实验性功能。这可能是一个原因。 - Anton Danilchenko
1
哦,是的。终于在这里找到了关于这个提案的描述:https://github.com/leebyron/ecmascript-export-default-from - Anton Danilchenko
3个回答

11

请使用以下语法:

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'; - Anton Danilchenko
1
而且使用星号也不起作用 - SyntaxError: export * as Button from './Button'; - Anton Danilchenko
如果你只想导入 Button,这样更符合语义化,你可以始终使用 import Button from './MyComponents/Button' - Przemysław Zalewski
你是对的,export * 在这种情况下不起作用。它只适用于上述语法导出的嵌套索引。我将编辑答案。 - Przemysław Zalewski
我的项目结构有更大的层次结构。这是我非常简化的示例,以了解如何在index.js文件中正确使用导入来使用每个组件目录。 - Anton Danilchenko
显示剩余2条评论

4
使用此构造方式:

export default from './Button';

我们需要使用 preset-stage-1

如何使用

  1. npm install babel-preset-stage-1 --save-dev
  2. 编辑 package.json 文件,并在 babelpresets 部分中添加 stage-1

package.json 的示例

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

更多信息

这是一个关于ECMAScript的提案-https://github.com/leebyron/ecmascript-export-default-from(仍在审核中)


0

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

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


尝试使用“export * from './Button'”导出所有内容,包括默认值。目前没有一行代码可以只导出默认值的解决方案。希望这可以帮到你。我已经更新了我的答案。 - Sagi_Avinash_Varma
看起来你完全不理解我的问题。而且 import Button from './Button'; 在我的原始问题中已经提到了,如果你仔细阅读的话。 - Anton Danilchenko
请查看我在您的回答中添加的第二条评论中的链接。 - Anton Danilchenko
@AntonDanilchenko,明白了。你在使用babel-plugin-add-module-exports吗? - Sagi_Avinash_Varma
好的,我明白了你的问题。按钮模块没有命名导出。因此,babel-plugin-add-module-exports将其视为CommonJS模块,这使得它无法进行直接默认导出。 - Sagi_Avinash_Varma
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接