EasyConcept

What is the difference between require and import in Node.js?

Technology:
Node.js
Experience:
Junior,
Mid-level

Quick answer

require is the CommonJS module system, which loads modules synchronously at runtime, while import is the ES module standard, which is statically analysed, asynchronous and supports top-level await and tree shaking.

Detailed explanation

CommonJS uses require() and module.exports; it is the default in .js files unless your package.json says otherwise. ES modules use import and export, enabled by "type": "module" in package.json or by using .mjs files. Imports are hoisted and resolved before the code runs, which allows tools to remove unused exports.

Differences to remember: ES modules require file extensions in relative imports, have no __dirname (use import.meta.url), and can only be loaded from CommonJS with dynamic import(). Dynamic import() works in both systems.

Example

javascript
// CommonJS
const express = require("express");
module.exports = { createApp };

// ES modules
import express from "express";
export function createApp() {}
  • Node.jsEasy

    What is the difference between package.json and package-lock.json?

    package.json lists your project's dependencies with allowed version ranges, while package-lock.json records the exact versions that were installed so every machine gets an identical dependency tree.

    Intern 路 Junior 路 Programming Fundamentals
  • Node.jsEasy

    What is Node.js and why is it called single-threaded?

    Node.js is a JavaScript runtime built on Chrome's V8 engine that runs your JavaScript on a single main thread and uses non-blocking I/O, so one thread can handle many concurrent connections.

    Intern 路 Junior 路 Asynchronous Programming
  • Node.jsEasy

    What is middleware in Express and how does it work?

    Middleware are functions that receive the request, response and a next callback; they run in the order they are registered and can modify the request, end the response or pass control on with next().

    Junior 路 Mid-level 路 REST API
  • Node.jsMedium

    What are streams in Node.js and why should you use them?

    Streams process data piece by piece as it arrives instead of loading it all into memory, which lets you handle large files and network data efficiently; they come in Readable, Writable, Duplex and Transform types.

    Mid-level 路 Senior 路 Performance
  • Node.jsMedium

    What is the difference between JWT and session-based authentication?

    Session authentication stores the login state on the server and gives the browser a session ID cookie, while JWT authentication gives the client a signed token that contains the user's claims so the server can verify it without storing state.

    Mid-level 路 Senior 路 Authentication