skip to Main Content

I have 3 classes in three different folders and based at country value at run time, the appropriate class object is created.

src/canada/index.ts
export const country = new Canada();


src/england/index.ts
export const country = new England();


src/spain/index.ts
export const country = new Spain();

There are some common code which needs to access the country object created. I tried to dynamically pass the path like import {country} from 'src/${country}/index.ts' but looks like dynamic import is not available in ES ["target": "ES2021", "module": "CommonJS"].

I have also tried const countryObj = await import('src/${country}/index.ts') , but I get this error

Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', 'nodenext', or 'preserve', and the 'target' option is set to 'es2017' or higher.

Is there a way I can have access to the country specific object from a different file?

2

Answers


  1. If you want to do dynamic import use the following syntax, within an async function or a callback approach.

     const {country: _country} = await import(`src/${country}/index.ts`);
     // or
     import(`src/${country}/index.ts`).then(({country: _country}) => { 
        console.log(country);
     });
    
    Login or Signup to reply.
  2. There!

    1. Dynamic Import: Use dynamic import to import the appropriate class
      object based on the country value. Dynamic import allows you to
      import modules conditionally at runtime.

    2. Construct the Import Path: Construct the import path dynamically
      based on the country value.

      async function getCountryObject(country) {
      let countryObject;
      try {
      // Construct the import path based on the country value
      const modulePath = ./${country}/index.js;

      // Dynamically import the module based on the constructed path
      const module = await import(modulePath);
      
      // Access the country object from the imported module
      countryObject = module.country;
      

      } catch (error) {
      // Handle any errors related to dynamic import
      console.error(‘Error importing country module:’, error);
      }

      return countryObject;
      }

      // Usage
      const country = ‘canada’; // Replace with the actual country value at runtime
      getCountryObject(country)
      .then(countryObject => {
      // Use the country object as needed
      console.log(countryObject);
      });

    Enjoy!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search