DEV Community

Bosco Domingo
Bosco Domingo

Posted on

JavaScript imports guide

Default import

import process from "node:process";

process.env.MY_VAR
Enter fullscreen mode Exit fullscreen mode
  • Brings in the default export of a module.
  • Shorthand for import { default as process } from "node:process".
  • Returns the live object (including this context), so process.on etc. work correctly.
  • Usage: modules with a default export defined that require state.

Named import

import { env } from "node:process";

env.MY_VAR
Enter fullscreen mode Exit fullscreen mode
  • Brings only the explicitly exported property as a raw, static reference (this = undefined).
  • Reduces bundle size (although tree-shakers are quite good at this, it will make compilation faster).
  • Usage: pure or stateless functions and constants.

Namespace import

import * as process from "node:process";

process.env.MY_VAR
process.on(...) // Fails
Enter fullscreen mode Exit fullscreen mode
  • Collects all exports into a single frozen module namespace object (properties are immutable).
  • Methods relying on this break (e.g. process.on), since they’re just functions detached from the real object.
  • Usage: static values/functions, not for stateful objects like process.

Side-effect import

import "node:process"; // Add a comment to explain why that import is there
Enter fullscreen mode Exit fullscreen mode
  • Runs the module’s top-level code but imports nothing.
  • Usage: polyfills, patches, or setup code.

Mixed imports

import process, { env } from "node:process";
Enter fullscreen mode Exit fullscreen mode
  • Combine default and named imports in one statement.
  • Handy when you want both the live object and specific named bindings.

Type-only import (TypeScript)

import type { MyComponent } from "./MyComponent.tsx";

/** @see MyComponent */
const MyComponentLazy = React.lazy(() => import("./MyComponent.tsx")
Enter fullscreen mode Exit fullscreen mode
  • Imports only type information, erased at runtime.
  • Guarantees no runtime code is included.
  • Usage: bringing type info, linking to lazily imported modules

JSON import (with import assertions)

import config from "./config.json" assert { type: "json" };
Enter fullscreen mode Exit fullscreen mode
  • Imports a JSON file directly as a parsed object.
  • Errors if assertion is not passed

Rule of thumb:

  • Use default import for live objects that have methods with this.
  • Use named import when you need just a piece of the module.
  • Use namespace import only for modules with pure functions/values.
  • Use type import to keep type dependencies clean (TS only).
  • Use JSON import for configs/data files that should be parsed automatically.
  • Use side-effect import very sparingly, for things that must run once globally, and make sure to document it.

Top comments (0)