P粉7153042392023-08-28 09:40:08
I thought, "I want to use a clean approach", one that is easy to understand. Therefore, the following may be useful -
<强>1. Default export-
This is useful for exporting only a single object, function or variable. During the import process we can import using any name.
// x.js export default function xFunc() { return { text: "text" }; } //y.js import xFunc from "./x.js"; export default function yFunc() { return { ...xFunc(), text2: "text2", }; } // import y in any file import yFunc from "./y"; console.log(yFunc());
The default export can also be used like this-
This is useful because we can use any name for fun since it is the default export with a name (so we can remember the name) and import with any name.
// x.js function xFunc() { return { text: "text" }; } export { xFunc as default }; // y.js import anyName from "./x.js"; function yFunc() { return { ...anyName(), text2: "text2", }; } export { yFunc as default }; // import y in any file import anyName from "./y"; console.log(anyName());
<强>2. Named export (recommended)-
This is useful for exporting multiple values. During the import process, the same name must be used to avoid confusion between export and import names.
// x.js export const xFunc = () => { text: "text" }; //y.js import { xFunc } from "./x.js"; export const yFunc = () => { return { ...xFunc(), text2: "text2", }; }; // import y in any file import { yFunc } from "./y"; console.log(yFunc());
edit--
Named exports can also be used in this way (without using const and arrow functions)
// x.js function xFunc() { return { text: "text" }; } export { xFunc }; //y.js import { xFunc } from "./x.js"; function yFunc() { return { ...xFunc(), text2: "text2", }; } export { yFunc }; // import y in any file import { yFunc } from "./y"; console.log(yFunc());