Dynamic Import with Computed Paths
You'll learn how to build module paths dynamically at runtime, making your imports flexible and data-driven.
Building Paths on the Fly
Until now, you've seen dynamic imports with static strings like import('./module.js'). But the real power emerges when you compute the path at runtime using variables, template literals, or any expression that produces a string.
Think of it like ordering from a restaurant menu where the dish name comes from a variable—you don't know what you're getting until runtime!
Using Variables and Template Literals
You can construct the import path using any JavaScript expression:
// Using a variable
const moduleName = 'userModule';
const module = await import(`./${moduleName}.js`);
// Using template literals with data
const language = 'es';
const translations = await import(`./i18n/${language}.js`);
// Based on user input or configuration
const theme = userPreferences.theme; // 'dark' or 'light'
const themeModule = await import(`./themes/${theme}.js`);
Real-World Pattern: Conditional Loading
async function loadFeature(featureName) {
try {
// Path built from function parameter
const module = await import(`./features/${featureName}.js`);
return module.default;
} catch (error) {
console.error(`Failed to load ${featureName}:`, error);
return null;
}
}
// Load different modules based on runtime conditions
const feature = await loadFeature('dashboard');
This is incredibly useful for loading locale files, themes, plugins, or any module where the choice depends on runtime data like user settings, API responses, or environment variables.
Key Takeaway: Dynamic imports accept any expression that evaluates to a string, letting you build module paths from variables, template literals, or computed values—perfect for runtime module selection based on user data or application state.