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
If you want to do dynamic import use the following syntax, within an
async
function or a callback approach.There!
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.
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
;} 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!