0

I am building the project structure and I was creating some modules, where I needed to import according to the route the user is on.

# my folder structure

modules
-- user
-- client
-- index
# my code 

// get constructor 
const  const constructor = await getConstructor( 'user' ); // get the constructor

// index
export const getConstructor = async ( module ) => {
    const constructor = await require(`./${module}`).create; // option 1 
    const constructor = await import(`./${module}`).then( constructor => constructor.create ); // option 2
    return constructor;
}


// module - user
const create = ( data ) => {
    // behavior
    // ...

}

export {
    create,
    delete,
    otherFunctions
}

My question is what is the best way, in terms of performance, to dynamically import the create function, whether option 1 or 2 or even if there is another way.

Any suggestion?

2
  • Can I deduce from your problem that you want to import some stuff on demand ? Commented Apr 13, 2020 at 11:55
  • basically, in the user file, for example, there would be some functions, such as create, delete, other functions. And on that driver, I just wanted to get the create function, without getting the rest. I'm thinking, in terms of performance.
    – martinho
    Commented Apr 13, 2020 at 12:00

1 Answer 1

1

I think you should take a look at es-module loader, it is a way for managing asynchronous imports 'Lazy loading', and in terms of performance, I think also this is good solution. Which lead us to your second option.

If you are using a webpack, you can take a look of a concept called Code splitting.

1
  • Thanks for the reply, I'll take a look: D
    – martinho
    Commented Apr 13, 2020 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.