Sto cercando di creare un modulo che esporta più classi ES6. Diciamo che ho la seguente struttura di directory:
my/
└── module/
├── Foo.js
├── Bar.js
└── index.js
Foo.js
e Bar.js
ciascuno esporta una classe ES6 predefinita:
// Foo.js
export default class Foo {
// class definition
}
// Bar.js
export default class Bar {
// class definition
}
Al momento ho il mio index.js
impostare in questo modo:
import Foo from "./Foo";
import Bar from "./Bar";
export default {
Foo,
Bar,
}
Tuttavia, non riesco a importare. Voglio essere in grado di farlo, ma le classi non sono state trovate:
import {Foo, Bar} from "my/module";
Qual è il modo corretto di esportare più classi in un modulo ES6?
risposte:
114 per risposta № 1Prova questo nel tuo codice:
import Foo from "./Foo";
import Bar from "./Bar";
export { // without default
Foo,
Bar,
}
A proposito, puoi anche farlo in questo modo:
//bundle.js
export Foo from "./Foo"
export Bar from "./Bar"
//and import somewhere..
import { Foo, Bar } from "./bundle"
utilizzando 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";
La differenza per export default
è che puoi esportare qualcosa e applicare il nome dove lo importi
// export default
const Func = () {}
export default Func;
// import it
import Foo from "./func"
10 per risposta № 2
Spero che questo ti aiuti:
// 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 per risposta № 3
La risposta di @webdeb non ha funzionato per me, ho colpito un unexpected token
errore durante la compilazione di ES6 con Babel, eseguendo esportazioni predefinite denominate.
Questo ha funzionato per me, tuttavia:
// 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 per risposta № 4
Per esportare le istanze delle classi è possibile utilizzare questa sintassi:
// 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();