Open In App

Explain the difference between require() and import in Node.

require() in NodeJS:

import in NodeJS:

Difference between require() and import in NodeJS:

require() import
Uses CommonJS syntax: require('module') Uses ES6 syntax: import module from 'module'
Used for importing modules synchronously Used for importing modules asynchronously (dynamic)
Supports both CommonJS modules and ES modules Supports only ES modules (requires .mjs extension)
No explicit support for default exports Supports default exports (import module from 'module')
Supports named exports via destructuring Supports named exports directly (import { name } from 'module')
Does not support static analysis Supports static analysis (enables tree shaking)
Does not supported dynamic importing Supports dynamic importing (import() function)
Synchronous, loads modules on demand Asynchronous, loads modules only when needed
Not supported in browser environments Supported in modern browsers with module support

require() and import serve the same purpose of loading modules, but import is the newer and more feature-rich approach introduced in modern JavaScript. It’s especially useful in browser environments and when working with ES6 modules

Article Tags :