如何动态获取函数

问题描述 投票:0回答:1

我有 3 个 diff 文件,名为 newConfig、historyConfig 和 DraftConfig .tsx

在 newConfig 里面我有

export const config1 = [{1:"new",2:"new new"}]

在historyConfig里面我有

export const config1 = [{1:"his",2:"his his"}]

在 DraftConfig 里面我有

export const config1 = [{1:"draf",2:"draf draf"}]

在另一个文件中,我想根据参数从 diff 文件中导出 config1:

const switchIt = async (currentType: string, currentMode: string) => {
  try {
    const pathName = currentType.concat(currentMode)
    console.log(pathName) //output: NewMerchant
    //This cannot work 
    const configModule = await import(`@WebFEFrameUtilities/applicationConfigs/${pathName}Config`);

    // But this can work >> const configModule = await import(`@WebFEFrameUtilities/applicationConfigs/NewMerchantConfig`);

    const currentConfig = configModule.config1;
    console.log("Success >>>>", currentConfig) 
    return currentConfig;
  } catch (error) {
    console.log("err")
  }
};

我可以知道为什么吗

const configModule = await import(`@WebFEFrameUtilities/applicationConfigs/${pathName}Config`);

无法工作?但是

const configModule = await import(`@WebFEFrameUtilities/applicationConfigs/NewMerchantConfig`);

可以工作吗?

或者也许如何才能使动态的能够工作?

javascript reactjs import dynamic-function
1个回答
0
投票

这是因为打包工具(如webpack)不会分析包含var的路径,它只是帮助我们转换精确的字符串路径,所以你需要使用相对路径但'@'并添加文件扩展名来查找你导入的文件。

© www.soinside.com 2019 - 2024. All rights reserved.