How to get the return value of "Export Default" when importing?
P粉595605759
P粉595605759 2023-08-27 23:36:46
0
1
576
<p>Simply, I have a <code>js</code> file whose export defaults return an object. </p> <pre class="brush:js;toolbar:false;">// x.js export default ()=>({ text: 'text' }) </pre> <p>I want to import it into another <code>js</code> file and merge it with its data (kind of extend it). Now I'm doing this: </p> <pre class="brush:js;toolbar:false;">// y.js import x from './x.js'; const obj = x() export default ()=>({ ...obj, text2: "text2" }) </pre> <p>It works, but it's not clean. Is there an easier way to do this? </p>
P粉595605759
P粉595605759

reply all(1)
P粉715304239

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());
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!