Próbuję utworzyć moduł, który eksportuje wiele klas ES6. Powiedzmy, że mam następującą strukturę katalogów:
my/
└── module/
├── Foo.js
├── Bar.js
└── index.js
Foo.js
i Bar.js
każdy eksportuje domyślną klasę ES6:
// Foo.js
export default class Foo {
// class definition
}
// Bar.js
export default class Bar {
// class definition
}
Obecnie mam swoje index.js
skonfiguruj tak:
import Foo from "./Foo";
import Bar from "./Bar";
export default {
Foo,
Bar,
}
Nie mogę jednak zaimportować. Chcę móc to zrobić, ale klas nie znaleziono:
import {Foo, Bar} from "my/module";
Jaki jest prawidłowy sposób eksportowania wielu klas w module ES6?
Odpowiedzi:
114 za odpowiedź № 1Wypróbuj to w swoim kodzie:
import Foo from "./Foo";
import Bar from "./Bar";
export { // without default
Foo,
Bar,
}
Przy okazji możesz to zrobić w ten sposób:
//bundle.js
export Foo from "./Foo"
export Bar from "./Bar"
//and import somewhere..
import { Foo, Bar } from "./bundle"
Za pomocą 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";
Różnica do export default
polega na tym, że możesz coś wyeksportować i zastosować nazwę w miejscu, w którym go importujesz
// export default
const Func = () {}
export default Func;
// import it
import Foo from "./func"
10 dla odpowiedzi nr 2
Mam nadzieję że to pomoże:
// 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();
2 dla odpowiedzi nr 3
Odpowiedź @ webdeb nie zadziałała, trafiłem unexpected token
błąd podczas kompilowania ES6 z Babelem, podczas eksportowania nazwanego domyślnego.
Działa to jednak dla mnie:
// 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"
0 dla odpowiedzi nr 4
Aby wyeksportować wystąpienia klas, możesz użyć tej składni:
// 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();