Dynamic import

3 snippets across 3 stacks - JavaScript, Python, React

JSJavaScript

Dynamic Import

JS · Modules
Syntax
const module = await import("./module.js");
Example
async function loadEditor() {
  const { EditorView } = await import("./editor.js");
  return new EditorView(document.getElementById("editor"));
}

// Conditional loading
if (needsCharting) {
  const { renderChart } = await import("./charts.js");
  renderChart(data);
}

Note Returns a promise that resolves to the module namespace. Ideal for code-splitting, lazy loading, and conditional imports. Works at runtime, not just at the top of a file.

PYPython

Dynamic Imports

PY · Modules & Imports
Syntax
import importlib
mod = importlib.import_module('name')
Example
import importlib

# Import module by string name
json_mod = importlib.import_module("json")
result = json_mod.dumps({"dynamic": True})
print(result)

# Reload a module during development
# importlib.reload(my_module)
Output
{"dynamic": true}

Note Dynamic imports are useful for plugin systems and lazy loading. importlib.reload() re-executes the module but existing references to old objects are not updated.

REReact

Suspense & Lazy Loading

RE · Patterns
Syntax
const LazyComponent = React.lazy(() => import('./Component'));

<Suspense fallback={<Loading />}>
  <LazyComponent />
</Suspense>
Example
import { lazy, Suspense, useState } from 'react';

const AdminPanel = lazy(() => import('./AdminPanel'));
const UserDashboard = lazy(() => import('./UserDashboard'));

function App({ role }) {
  return (
    <Suspense fallback={<div className="spinner">Loading...</div>}>
      {role === 'admin' ? <AdminPanel /> : <UserDashboard />}
    </Suspense>
  );
}

Note React.lazy only works with default exports. For named exports, create an intermediate module that re-exports as default. Suspense can also wrap components that use the use() hook to read promises in React 19.

Frequently asked questions

How does JavaScript handle dynamic import?
This task is covered in 3 stacks on this page: JavaScript, Python, React. The "Dynamic Import" snippet in JavaScript uses `const module = await import("./module.js");`.
Which code does the JavaScript example use?
The "Dynamic Import" snippet uses `const module = await import("./module.js");`, from the Modules section of the JavaScript cheat sheet.
Which stacks cover "dynamic import" on this page?
JavaScript, Python, React. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Dynamic Import": Returns a promise that resolves to the module namespace. Ideal for code-splitting, lazy loading, and conditional imports. Works at runtime, not just at the top of a file.