Using dynamic import()
syntax, which is a function and allows you to conditionally import modules at runtime. Here’s how to implement it:
import { mainURL } from '../../support/helperFunctions.js';
let dataModule;
if (mainURL.includes('dev')) {
dataModule = import('../../../data/dataDev.js');
} else {
dataModule = import('../../../data/data.js');
}
// Use an async function to handle the dynamic import and access the module's exports
async function loadData() {
const { coreData, lastUpdated } = await dataModule;
console.log(coreData, lastUpdated);
// You can now use coreData and lastUpdated as needed
}
// Call loadData() to trigger the import
loadData();
import()
returns a promise, so we can use await
to get the module's exports.import()
is asynchronous, you need to wrap it in an async function to handle the promise.(async () => {
if (somethingIsTrue) {
// import module for side effects
await import("/modules/my-module.js");
}
})();
Refer to this article: Dynamic Imports MDN