developer tip

ES6 모듈에서 여러 클래스 내보내기

optionbox 2020. 8. 7. 08:19
반응형

ES6 모듈에서 여러 클래스 내보내기


여러 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,
}

Btw, 다음과 같이 할 수도 있습니다.

// 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'

도움이 되었기를 바랍니다:

// 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();

@webdeb의 대답이 저에게 효과가 없었습니다. unexpected tokenES6를 Babel로 컴파일하고 명명 된 기본 내보내기를 수행 할 때 오류가 발생했습니다.

그러나 이것은 나를 위해 일했습니다.

// 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';

For exporting the instances of the classes you can use this syntax:

// 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();

참고URL : https://stackoverflow.com/questions/38340500/export-multiple-classes-in-es6-modules

반응형