Require vs Import in JavaScript: Key Differences and Usage
require is a CommonJS syntax used mainly in Node.js for loading modules synchronously, while import is an ES6 module syntax that supports static loading and is standard in modern JavaScript environments. import allows static analysis and tree shaking, making it preferred for frontend and modern backend code.Quick Comparison
Here is a quick side-by-side comparison of require and import in JavaScript.
| Factor | require | import |
|---|---|---|
| Module System | CommonJS | ES6 Modules (ESM) |
| Syntax Type | Function call | Keyword statement |
| Loading | Synchronous | Static (analyzed at compile time) |
| Usage Environment | Node.js (mostly) | Browsers and modern Node.js |
| Support for Tree Shaking | No | Yes |
| Can be used conditionally | Yes | No (static imports only) |
Key Differences
require is a function used in CommonJS modules, primarily in Node.js. It loads modules synchronously at runtime, which means the code waits until the module is fully loaded before continuing. This makes it simple but less optimized for modern workflows.
import is part of the ES6 module system and uses static syntax. It is statically analyzed and loaded before runtime, allowing JavaScript engines to analyze dependencies before running the code. This enables features like tree shaking, which removes unused code to reduce bundle size.
Another key difference is that require can be called conditionally inside functions or blocks, while import statements must be at the top level of the file and cannot be used conditionally. This enforces a clear module structure and better optimization.
Code Comparison
Here is how you load and use a module that exports a function using require in Node.js.
const greet = require('./greet'); greet('Alice');
import Equivalent
The same module usage with import syntax looks like this in ES6 modules.
import greet from './greet.js'; greet('Alice');
When to Use Which
Choose require when working in older Node.js projects or when you need to load modules conditionally at runtime. It is simple and widely supported in Node.js environments.
Choose import for modern JavaScript development, especially in frontend projects or new Node.js versions that support ES modules. It enables better optimization, static analysis, and cleaner syntax.
Key Takeaways
require is CommonJS and synchronous; import is ES6 and statically analyzed.import supports static analysis and tree shaking, improving performance.require can be used conditionally; import must be top-level.require in legacy Node.js; use import in modern JS projects.import is the future standard for JavaScript modules.