🟒 EasyModern JSπŸ“– Theory Question

What are dynamic imports and why are they useful?

πŸ’‘

Hint

import() returns a Promise β€” enables code splitting, conditional loading, lazy loading

Full Answer

Dynamic imports (import()) load modules on demand, returning a Promise. Enables code splitting.

// Static β€” always loads at startup
import { parse } from 'csv-parser';

// Dynamic β€” loads only when needed
async function handleUpload(file) {
  if (file.type === 'text/csv') {
    const { parse } = await import('csv-parser'); // loaded now
    return parse(file);
  }
}

// React code splitting
const Chart = React.lazy(() => import('./HeavyChart'));

// Conditional loading
const lang = navigator.language;
const { messages } = await import(`./i18n/${lang}.js`); // dynamic path

// User-triggered loading
button.onclick = async () => {
  const { default: Editor } = await import('./editor.js');
  new Editor(container);
};

// Access default + named exports
const mod = await import('./math.js');
mod.default; // default export
mod.add;     // named export

Benefits: Smaller initial bundle, faster page load, load features only when needed.

πŸ’‘ Webpack and Vite automatically create separate JS chunks for each dynamic import. Use loading states while the chunk loads.

More Modern JS Questions

🟑 MediumWhat are generators and when would you use them?β†’πŸŸ’ EasyWhat is optional chaining (?.) and nullish coalescing (??)?β†’πŸŸ’ EasyWhat are tagged template literals and what are they used for?β†’πŸŸ’ EasyExplain destructuring for objects and arrays β€” including defaults, renaming, rest, and nesting.β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint