Questions
What is the difference between `require` and `import` in Node.js?
The Scenario
You are working on a new Node.js project and need to decide whether to use CommonJS modules (require) or ES modules (import).
The Challenge
Explain the difference between require and import. What are the pros and cons of each approach, and which one would you choose for a new project?
A junior engineer might think that they are interchangeable. They might not be aware of the difference between CommonJS and ES modules, or the implications of choosing one over the other.
A senior engineer would be able to provide a detailed explanation of the differences between `require` and `import`. They would also be able to explain the benefits of using ES modules and would have a clear recommendation for which one to use in a new project.
Step 1: Understand the Two Module Systems
| Feature | require (CommonJS) | import (ES Modules) |
|---|---|---|
| Syntax | Dynamic, can be called anywhere in the code. | Static, must be at the top level of a module. |
| Loading | Synchronous, loads modules at runtime. | Asynchronous, loads modules before execution. |
| Tree shaking | Not supported. | Supported, allows bundlers to remove unused code. |
| Compatibility | Supported in all versions of Node.js. | Supported in modern versions of Node.js. |
Step 2: Choose the Right Tool for the Job
For a new project, you should use ES modules (import). They are the standard for JavaScript, and they have several benefits over CommonJS modules, such as tree shaking and better support for circular dependencies.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
require (CommonJS):
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// main.js
const { add } = require('./math.js');
console.log(add(2, 3));import (ES Modules):
To use ES modules in Node.js, you need to either use the .mjs file extension or set "type": "module" in your package.json file.
// math.mjs
export function add(a, b) {
return a + b;
}
// main.mjs
import { add } from './math.mjs';
console.log(add(2, 3)); Practice Question
You are building a library and you want to make sure that it can be used by both CommonJS and ES modules. What should you do?