【问题标题】:(js): dynamically import modules(js):动态导入模块
【发布时间】:2020-07-25 23:23:18
【问题描述】:

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

# 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 函数的最佳方式是什么,无论是选项 1 还是 2,或者即使还有其他方式。

有什么建议吗?

【问题讨论】:

  • 我可以从你的问题中推断出你想要import一些按需的东西吗?
  • 基本上,在用户文件中,例如,会有一些函数,例如createdelete,其他函数。在那个驱动程序上,我只想得到create 函数,而没有得到其余的。我在考虑,就性能而言。

标签: javascript import export es6-modules es6-module-loader


【解决方案1】:

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

如果你使用的是 webpack,你可以看看一个叫做 Code splitting 的概念。

【讨论】:

  • 感谢回复,我去看看:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 2023-02-01
  • 1970-01-01
  • 2020-02-16
  • 2020-01-20
  • 1970-01-01
  • 2017-07-13
相关资源
最近更新 更多