Untitled Lesson
Skill Matrix
UNLOCK NODES BY LEARNING NEW TAGS.
A relative import `import { helper } from "./utils"` (no extension) throws `ERR_MODULE_NOT_FOUND` in native Node ESM but works fine with webpack. Why?
💻 Code Challenge | +75 XP
Convert a CommonJS module that uses __dirname to read a local JSON config file into a valid ES Module, using import.meta.url and fileURLToPath.
A CommonJS file trying to `require()` a package that shipped as ESM-only (like modern chalk) crashes with ERR_REQUIRE_ESM. Reorder the steps to fix it without rewriting the whole file to ESM.
Task: Reorder the blocks in logical sequence to solve the problem.
A.D.A. Interface
Adaptive Didactic Assistant

Pascual Vila
Frontend Instructor // Code Syllabus
The Error //
Omitting the file extension in a relative import under native ESM
// Wrong — throws ERR_MODULE_NOT_FOUND
import { db } from "./database";
// Correct
import { db } from "./database.js";The Solution //
Node's native ESM resolver, unlike bundler resolvers (webpack, Vite), does not guess file extensions — it requires the exact extension in every relative import specifier. Add the .js (or .mjs) extension explicitly to every local relative import.
The Error //
Using __dirname or __filename inside a file after switching to "type": "module"
// Wrong — ReferenceError: __dirname is not defined
const configPath = path.join(__dirname, "config.json");
// Correct
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
const __dirname = dirname(fileURLToPath(import.meta.url));
const configPath = join(__dirname, "config.json");The Solution //
These CommonJS-only globals are undefined in ES Modules and throw a ReferenceError. Reconstruct the equivalent path using import.meta.url passed through node:url's fileURLToPath(), combined with node:path's dirname().