导出 ES6 模块中的多个类

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

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

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

// 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模块中导出多个类的正确方法是什么?


答案 1

请在代码中尝试以下操作:

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

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'

答案 2

希望这有帮助:

// Export (file name: my-functions.js)
export const MyFunction1 = () => {}
export const MyFunction2 = () => {}
export const MyFunction3 = () => {}

// if using `eslint` (airbnb) then you will see warning, so do this:
const MyFunction1 = () => {}
const MyFunction2 = () => {}
const MyFunction3 = () => {}

export {MyFunction1, MyFunction2, MyFunction3};

// Import
import * as myFns from "./my-functions";

myFns.MyFunction1();
myFns.MyFunction2();
myFns.MyFunction3();


// OR Import it as Destructured
import { MyFunction1, MyFunction2, MyFunction3 } from "./my-functions";

// AND you can use it like below with brackets (Parentheses) if it's a function 
// AND without brackets if it's not function (eg. variables, Objects or Arrays)  
MyFunction1();
MyFunction2();