Imports the module’s default export (if one exists).
Shorthand for import { default as X } from "Y".
If the default export is an object (for example the process object in Node.js), calling methods via that object (e.g., process.on(...)) uses the correct object as the this context.
Use this when the module exports a stateful object or one “main” entity.
Named import
import{env}from"node:process";env.MY_VAR
Brings only the explicitly exported property as a raw, static reference.
If you import a function or method via named import and then call it without its owning object, you may lose the original this binding (so this may be undefined).
Reduces bundle size (although tree-shakers are quite good at this, it will make compilation faster).
Still runs code in the imported module.
Usage: pure or stateless functions and constants, reducing import size.
Namespace import
import*asprocessfrom"node:process";process.env.MY_VAR// undefinedprocess.default.env.MY_VAR// "All good!"
Collects all exports into a single frozen module namespace object (properties are immutable).
Renames the default export to default. All others are kept the same.
Methods called via namespace.method() will still have namespace as the calling object (so this inside the method will refer to namespace, assuming the method uses this).
Usage: accessing all exports from a module without having to import each one.
Side-effect import
import"node:process";// Add a comment to explain why that import is there
Runs the module’s top-level code but imports nothing.
Usage: polyfills, patches, or setup code.
Mixed imports
importprocess,{env}from"node:process";
Combine default and named imports in one statement.
Handy when you want both the live object and specific named bindings.
Top comments (0)