What is the difference between require and import?
require (CommonJS) is synchronous and traditionally used in Node.js. import (ES Modules) is asynchronous, is the JavaScript standard, and is supported in Node.js 13+ with type: 'module' in package.json. require uses module.exports, import uses export/export default.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Node.js Modules and require Interview Questions CommonJS vs ES Modules
Five steps: resolution (find the file), loading (read content), wrapping (wrap in a function with exports, require, module, __filename, __dirname), evaluation (execute the function), and caching (store for future requires). Cached modules return the same instance on subsequent requires.
When module A requires B and B requires A, Node.js returns a partial (incomplete) module.exports object. When B requires A, it gets the current state of A's exports, which may be incomplete. Best practice: avoid circular dependencies by refactoring shared logic into a third module.
Initially, exports and module.exports point to the same object. If you reassign exports (exports = { ... }), it breaks the reference and module.exports is not updated. Always use module.exports = { ... } or exports.property = value (adding properties, not reassigning).
Still have questions?
Browse all our FAQs or reach out to our support team
