在ES6模块中导出多个类 [英] Export multiple classes in ES6 modules

查看:778
本文介绍了在ES6模块中导出多个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个导出多个ES6类的模块。假设我有以下目录结构:

I'm trying to create a module that exports multiple ES6 classes. Let's say I have the following directory structure:

my/
└── module/
    ├── Foo.js
    ├── Bar.js
    └── index.js

Foo.js Bar.js 每个导出默认的ES6类:

Foo.js and Bar.js each export a default ES6 class:

// Foo.js
export default class Foo {
  // class definition
}

// Bar.js
export default class Bar {
  // class definition
}

我目前有我的 index.js 设置如下:

I currently have my index.js set up like this:

import Foo from './Foo';
import Bar from './Bar';

export default {
  Foo,
  Bar,
}

但是,我无法导入。我想要这样做,但是找不到类:

However, I am unable to import. I want to be able to do this, but the classes aren't found:

import {Foo, Bar} from 'my/module';

在ES6模块中导出多个类的正确方法是什么?

What is the correct way to export multiple classes in an ES6 module?

推荐答案

在您的代码中尝试这样:

Try this in your code:

import Foo from './Foo';
import Bar from './Bar';

export { // without default
  Foo,
  Bar,
}

Btw,你也可以这样做:

Btw, you can also do it this way:

//bundle.js
export Foo from './Foo'
export Bar from './Bar'

//and import somewhere..
import { Foo, Bar } from './bundle'

使用导出

export const MyFunction = () => {}
export const MyFunction2 = () => {}

const Var = 1;
const Var2 = 2;
export {
   Var, Var2
}


// Then import it this way
import {MyFunction, MyFunction2, Var, Var2 } from './foo-bar-baz';

导出默认值的区别

是您可以导出东西,并应用导入它的名称

is that you can export something, and apply the name where you import it

// export default
const Func = () {}
export default Func;

// import it
import Foo from './func'

这篇关于在ES6模块中导出多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆