to put it simply, I have a js
file with export default that return an object.
// x.js
export default ()=>({
text: 'text'
})
I wanna import it in another js
file and merge it with its data (kinda extend it). Right now I'm doing it like this:
// y.js
import x from './x.js';
const obj = x()
export default ()=>({
...obj,
text2: "text2"
})
It is working but not clean. Is there any simpler way to do this?
From "I want to use a clean approach" , I assume, an approach that is easy to understand. So, the following approaches could be useful-
1. Default Exports-
This is useful to export only a single object, function, or variable. During the import, we can use any name to import.
// 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());
Default Exports can also be used in this way-
This is useful as we can use any name for fun because it is a 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 Exports (Recommended)-
This is useful to export several values. During the import, it is mandatory to use the same name which avoids confusion between exported and imported name.
// 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 like this (without using const and arrow function)
// 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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.