Enabling ESM in Node.js
What you'll learn: How to configure Node.js to recognize and execute ES modules instead of defaulting to CommonJS.
Why Configuration Matters
By default, Node.js treats .js files as CommonJS modules (using require() and module.exports). To use modern ES module syntax (import and export) in your Node.js projects, you need to explicitly tell Node.js: "Hey, I'm using ESM here!"
Think of it like setting your car's GPS to metric vs. imperial units — the car needs to know which system you're using before it can interpret your input correctly.
Two Ways to Enable ESM
Method 1: The package.json Type Field
Add "type": "module" to your package.json:
{
"name": "my-project",
"version": "1.0.0",
"type": "module"
}
Now all .js files in your project are treated as ES modules. You can use import and export freely.
Method 2: The .mjs Extension
Rename individual files from .js to .mjs:
app.mjs
utils.mjs
Node.js automatically recognizes .mjs files as ES modules, regardless of your package.json settings. This is useful for gradual migration — you can mix CommonJS and ESM files in the same project.
Which Should You Choose?
Use "type": "module" for new projects or when converting an entire codebase. Use .mjs when you need to run ESM alongside existing CommonJS files during a transition period.
Key Takeaway: Enable ES modules in Node.js by setting "type": "module" in package.json (project-wide) or using the .mjs file extension (file-specific).