我试图创建一个模块,导出多个ES6类。假设我有如下的目录结构:

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

Foo.js和Bar.js各自导出一个默认的ES6类:

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

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

我现在把index.js设置成这样:

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

export default {
  Foo,
  Bar,
}

但是,我无法导入。我希望能够做到这一点,但类没有找到:

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

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


当前回答

在你的代码中试试这个:

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

// without default
export {
  Foo,
  Bar,
}

顺便说一下,你也可以这样做:

// 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 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不同的是,你可以导出一些东西,并在导入它的地方应用名称:

// export default
export default class UserClass {
  constructor() {}
};

// import it
import User from './user'

其他回答

在你的代码中试试这个:

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

// without default
export {
  Foo,
  Bar,
}

顺便说一下,你也可以这样做:

// 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 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不同的是,你可以导出一些东西,并在导入它的地方应用名称:

// export default
export default class UserClass {
  constructor() {}
};

// import it
import User from './user'

要导出类的实例,可以使用以下语法:

// export index.js
const Foo = require('./my/module/foo');
const Bar = require('./my/module/bar');

module.exports = {
    Foo : new Foo(),
    Bar : new Bar()
};

// import and run method
const {Foo,Bar} = require('module_name');
Foo.test();

你可以做到。 导出{className, className等}

@webdeb的答案对我不起作用,我在用Babel编译ES6时遇到了一个意想不到的令牌错误,做命名默认导出。

然而,这对我来说很管用:

// Foo.js
export default Foo
...

// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
...

// and import somewhere..
import { Foo, Bar } from './bundle'
// export in index.js
export { default as Foo } from './Foo';
export { default as Bar } from './Bar';

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