How to get the return value of "Export Default" when importing?
P粉595605759
2023-08-27 23:36:46
<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>
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.
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.
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.
edit--
Named exports can also be used in this way (without using const and arrow functions)