Import()

3 snippets across 2 stacks - JavaScript, Python

Also written as import as · import all · from import

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.

Namespace Import

JS · Modules
Syntax
import * as name from "./module.js";
Example
import * as validators from "./validators.js";

const email = "[email protected]";
console.log(validators.isEmail(email));
console.log(validators.isNotEmpty(email));

Note Imports all named exports as a single object. The object is frozen (read-only). Useful when a module has many exports you want to use together.

PYPython

Basic Imports

PY · Modules & Imports
Syntax
import module
from module import name
import module as alias
Example
import json
from pathlib import Path
from collections import defaultdict, Counter
import numpy as np  # common alias convention

data = json.dumps({"key": "value"})
print(data)
Output
{"key": "value"}

Note Convention: standard library imports first, then third-party, then local. Separate groups with a blank line. Use isort to auto-format.

Frequently asked questions

How do you import()?
This task is covered in 2 stacks on this page: JavaScript, Python. 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 "import()" on this page?
JavaScript, Python. 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.