简体   繁体   中英

(js): dynamically import modules

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?

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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM