在 ES6 模块中导出多个类 [英] Export multiple classes in ES6 modules
问题描述
我正在尝试创建一个导出多个 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';
// without default
export {
Foo,
Bar,
}
顺便说一句,你也可以这样做:
Btw, you can also do it this way:
// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
export { default } from './Baz'
// and import somewhere..
import Baz, { Foo, Bar } from './bundle'
使用export
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';
与export default
的区别在于,您可以导出某些内容,并在导入时应用名称:
The difference with export default
is that you can export something, and apply the name where you import it:
// export default
export default class UserClass {
constructor() {}
};
// import it
import User from './user'
这篇关于在 ES6 模块中导出多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!