Dung (Donny) Nguyen

Senior Software Engineer

Require and Import

In Node.js, require and import are both used to bring modules or packages into our code, but they come from different module systems and have distinct behaviors. Here’s a breakdown of their differences and usage:

1. Module Systems

2. Syntax and Usage

3. Module Exporting

4. Compatibility

5. Use Cases

Example Comparison

Using require:

// CommonJS
const fs = require('fs');
fs.readFileSync('path/to/file');

Using import:

// ES6 Modules
import fs from 'fs';
fs.readFileSync('path/to/file');

In summary, use require for traditional CommonJS projects and import for projects configured to use ES6 modules. Both are valid in Node.js, but ES6 modules (import/export) are the standard moving forward.