繁体   English   中英

(js):动态导入模块

[英](js): dynamically import modules

我正在构建项目结构,并且正在创建一些模块,我需要根据用户所在的路线导入这些模块。

# 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
}

我的问题是,就性能而言,动态导入create function 的最佳方式是什么,无论是选项 1 还是 2,甚至还有其他方式。

有什么建议吗?

我认为你应该看看es-module loader ,它是一种管理异步导入“延迟加载”的方法,在性能方面,我认为这也是一个很好的解决方案。 这导致我们选择您的第二个选择。

如果你使用的是 webpack,你可以看看一个叫做代码拆分的概念。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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