search

Home  >  Q&A  >  body text

How to get the return value of "Export Default" when importing?

<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粉595605759P粉595605759502 days ago609

reply all(1)I'll reply

  • P粉715304239

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

    reply
    0
  • Cancelreply