What is the difference between require and import in Node.js?
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.
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.
// CommonJS
const express = require("express");
module.exports = { createApp };
// ES modules
import express from "express";
export function createApp() {}