ES6 import vs Node.js require differences

Day 31/50 – JavaScript Interview Question? Question: What is the difference between import and require()? Simple Answer: import is ES6 module syntax that's statically analyzed at compile time and supports tree-shaking. require() is CommonJS syntax used in Node.js, dynamically evaluated at runtime. import statements must be at the top level, while require() can be used conditionally. 🧠 Why it matters in real projects: Modern bundlers like Webpack and Vite use import for tree-shaking (removing unused code), significantly reducing bundle sizes. Understanding both is crucial since Node.js packages often use CommonJS while frontend code uses ES modules. 💡 One common mistake: Mixing import and require() syntax in the same file, or trying to use import conditionally inside if-statements (not allowed). Also, forgetting that require() is synchronous while dynamic import() is asynchronous. 📌 Bonus: // ES6 Modules (import) import React from 'react'; import { useState, useEffect } from 'react'; import * as utils from './utils'; import type { User } from './types'; // TypeScript // CommonJS (require) const express = require('express'); const { Router } = require('express'); // Key differences: // 1. Static vs Dynamic import { func } from './module'; // ✓ Top-level only const mod = require('./module'); // ✓ Can be anywhere if (condition) { import { func } from './module'; // ✗ SyntaxError const mod = require('./module'); // ✓ Works } // 2. Dynamic import (async ES6 feature) const module = await import('./module.js'); // ✓ Async loading // 3. Tree-shaking (import only) import { usedFunction } from 'lodash-es'; // Bundler removes unused functions ✓ const _ = require('lodash'); // Entire library included ✗ // 4. Named exports handling // ES6 export const name = 'Alice'; export default function() {} // CommonJS module.exports = { name: 'Alice' }; module.exports.name = 'Alice'; exports.name = 'Alice'; // Shorthand #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories