web-dev-qa-db-ja.com

ES6モジュールで複数のクラスをエクスポレートする

私は複数のES6クラスをエクスポートするモジュールを作成しようとしています。次のようなディレクトリ構造があるとしましょう。

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

Foo.jsBar.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モジュールで複数のクラスをエクスポートする正しい方法は何ですか?

87
ambient

あなたのコードでこれを試してください:

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'
160
webdeb

お役に立てれば:

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

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

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


// OR Import it as Destructured
import { MyFunction1, MyFunction2 } 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();
12
Syed

@ webdebの答えは私にはうまくいきませんでした、私はES6をBabelでコンパイルするときにunexpected tokenエラーを起こし、名前付きのデフォルトのエクスポートをしました。

これは私にとってはうまくいった、しかし:

// 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'
4
inostia
// 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';
2
PaoPao