Search code examples
javascriptreactjsimportdynamic-function

How to dynamically get the function


i have 3 diff files called newConfig, historyConfig and draftConfig .tsx

inside newConfig i have export const config1 = [{1:"new",2:"new new"}]

inside historyConfig i have export const config1 = [{1:"his",2:"his his"}]

inside draftConfig i have export const config1 = [{1:"draf",2:"draf draf"}]

and in another file I wanted to export config1 from diff files based on the param:

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")
  }
};

Can I know why

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

cannot work ? But

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

can work ?

or maybe how can make the dynamic one can work ?


Solution

  • This because the packaging tool(like webpack) will not analyze a path contains variable,it just help us to transform a exact string path,so you need use relative path but '@' and add file extension to find the file you importing.