I learnig reactjs (I'm from Angular, C#) and I broking my head with this....have this lib
const libA=()=>{
const fnA = () => {
return ...
}
const fnB = () => {
return ...
}
const fnC = () => {
return ...
}
return [fnA, fnB, fbC]
}
export default libA
And I consume libA this way
import { libA } from '../myLib.js'
const compB=()=>{
const [fnA, fnB, fnC] = myLib()
....
fnA()...
}
My problem is if I change order const [fnB, fnA, fnC ] is seted fns to wrong name (fnB=fnA,...). There is any that I can getr corretly fn only by name or I need put correctly name var order? My pain is if I have 10 fns I wiil need declare all vars since I use only 1, 2, or alterante vars from lib?
basically i want same thing like old way
function myLib(){
fnA: function () {return...},
fnB: function () {return...},
fnC: function () {return...},
}
myLib().fnA().....
thks
CodePudding user response:
Firstly, you exported libA
as a default export
so you should not import them as named imports
Eg: import libA from '../myLib.js'
instead of import { libA } from '../myLib.js'
.
Secondly, deconstructing arrays in JS mean that sequence/order of the array items are maintained. You cannot just change the order of elements when destructuring an array.
If you want to change the order of callbacks, you should export an object
instead of an array
in myLib.js
const libA=()=>{
const fnA = () => {
return ...
}
const fnB = () => {
return ...
}
const fnC = () => {
return ...
}
return {fnA, fnB, fbC}
}
export default libA
And you consume the libA
like
const compB=()=>{
const {fnA, fnB, fnC} = myLib()
....
fnA()...
}
PS: you have 10, 20 or more functions in that export.
You don't need to destructure the import, simply call them by .
import libA from '../myLib.js'
const compB=()=>{
....
libA()?.fnA() // conditionally call the fnA only if libA returns the function
}
CodePudding user response:
I think you don't need to scope all these libs inside a function to make it work as a module. Instead take advantage of the module object itself:
// libA.js
export const fnA = () => {
return ...
}
export const fnB = () => {
return ...
}
export const fnC = () => {
return ...
}
and in the other file
// anotherFile.js
import {fnA, fnB, fnC} from '../libA.js'
libA()
libB()
{...}