What is the difference between import and require in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
import belongs to ES modules, the standard module system built into JavaScript, while require() belongs to CommonJS, the older system Node.js used before ES modules existed. Inside an ES module require is not defined, so a file uses one system or the other.This answer is one piece of Chapter 7: Classes and Modules.
- JavaScript Classes & OOP
- Why This Chapter Is Here: Page Objects Are Just Classes
- Modules: require() vs import/export
- Build: Your First Page Object
- Practice and interview questions: Classes, OOP & Modules
Every test file starts by loading code from somewhere, so you meet this on line one. Playwright tests in this course use ES modules: import { test, expect } from '@playwright/test'.
Node decides which system a file uses before it runs a line. A .mjs file is always an ES module and a .cjs file is always CommonJS. A .js file follows the nearest package.json: "type": "module" makes it an ES module. Older projects and many answers online use require(), so you will still read it, but it is the other system.
The example is a .mjs file. Its import lines load node:path and node:url. The try block then calls require(), and Node throws ReferenceError: require is not defined, because ES modules have no require, exports or module.exports. Node also does not give an ES module __filename, so the file works out its own name from import.meta.url.
The last line shows import() written as a function. It loads a module while the code runs, and it returns a Promise, so you await it.
If you paste a snippet that uses require into an ES module test and get this ReferenceError, convert it to import rather than mixing the two.
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = fileURLToPath(import.meta.url);
console.log('loaded as an ES module:', path.basename(here));
try {
require('node:fs');
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
const { default: os } = await import('node:os');
console.log('dynamic import works too:', typeof os.platform);loaded as an ES module: modules.mjs ReferenceError: require is not defined dynamic import works too: function
package.json has "type": "module". A .js test file in it calls require('node:fs'). What happens?Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free