Javascript 是否可以使用 ES6/Babel 进行多个类导入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34648195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:40:35  来源:igfitidea点击:

Is it possible to do multiple class imports with ES6/Babel?

javascriptecmascript-6babeljs

提问by cdutson

I'm working on a react project (my first) and I've recently restructured my folder structure to make a bit more sense.

我正在做一个 React 项目(我的第一个项目),最近我重组了我的文件夹结构以使其更有意义。

To make my life easier, within my component folders, I have an index.jsfile which looks like the following:

为了让我的生活更轻松,在我的组件文件夹中,我有一个index.js如下所示的文件:

export * from './App';
export * from './Home';
export * from './PageWrapper';

(The idea was lifted from another StackOverflow Question)

(这个想法来自另一个StackOverflow 问题

In this case each of the files this index points to have a singular class export.

在这种情况下,该索引指向的每个文件都有一个单一的类导出。

Now in my main application, I try and do something like:

现在在我的主应用程序中,我尝试执行以下操作:

import {Home, App} from './containers/index';
//or
import Home from './containers/index';

Nothing works. I've found that if I separate them all out into individual lines pointing directly at the correct file, it works.

什么都行不通。我发现如果我将它们全部分成单独的行,直接指向正确的文件,它就可以工作。

import Home from './containers/Home';
import App from './containers/App';

So is it possible to import multiple classes the way I'm doing it, and I'm just not seeing it? Do I perhaps need to name them all (App as App)? Or is this simply an enforced limitation?

那么是否可以按照我的方式导入多个类,而我只是没有看到它?我可能需要将它们全部命名为 ( App as App) 吗?或者这仅仅是强制限制?

回答by Mario Tacke

You can export like this:

您可以像这样导出:

import App from './App';
import Home from './Home';
import PageWrapper from './PageWrapper';

export {
    App,
    Home,
    PageWrapper
}

Then, you can import like this wherever you need it:

然后,您可以在任何需要的地方像这样导入:

import { App, PageWrapper } from './index' //or similar filename

...

You can read more about importand exporthere. I also answered a similar question here.

您可以在此处阅读有关导入导出的更多信息。我也在这里回答了一个类似的问题。

回答by manhnguyen

I use export that looks something like this. In react it worked well

我使用看起来像这样的导出。在反应中它运作良好

export {default as PublicRoute} from './PublicRoute';
export {default as PrivateRoute} from './PrivateRoute';

Then, you can import like this wherever you need:

然后,您可以在任何需要的地方导入:

import {PublicRoute, PrivateRoute} from './config/router';
...

回答by Balaji.J.B

you can use this method

你可以用这个方法

import * React from 'react'