Enabling ESM
Enabiling ESM
Enabling ES Modules (ESM) in Node.js allows you to use import and export syntax instead of the traditional require and module.exports. Because Node.js was built on CommonJS, you have to explicitly tell the runtime to treat your code as ESM.
There are three primary ways to do this:
1. Using the package.json approach (Recommended)
This is the most common method for modern projects. By adding a single field to your project's configuration file, you turn the entire project into an ESM environment.
Step: Add
"type": "module"to yourpackage.json.Result: All
.jsfiles in that directory and subdirectories will be treated as ES Modules.
{
"name": "my-node-app",
"version": "1.0.0",
"type": "module",
"dependencies": { ... }
}2. Using the .mjs Extension
If you don't want to change the settings for your whole project, or if you are working in a legacy project that uses CommonJS, you can use a specific file extension.
Step: Rename your file from
app.jstoapp.mjs.Result: Node.js will automatically treat any
.mjsfile as an ES Module, regardless of what is in yourpackage.json.
3. Using the --input-type Flag
This is less common but useful for running small snippets of code directly from the command line or via "pipes."
node --input-type=module -e "import fs from 'fs'; console.log(fs.readdirSync('.'))"Key Changes When ESM is Enabled
Mandatory File Extensions
In CommonJS, you could do require('./utils'). In ESM, you must include the file extension when importing local files.
// Correct
import { data } from './utils.js';
// Error in ESM
import { data } from './utils';No "Magic" Globals
Variables like __dirname, __filename, and require are not available in ESM. You must use import.meta.url to reconstruct paths.
Strict Mode by Default
As mentioned previously, the moment you enable ESM, the entire file is executed in Strict Mode. You do not need to add "use strict"; at the top.
JSON Imports
In CommonJS, you could easily require('./data.json'). In ESM, importing JSON requires "Import Attributes" (supported in newer Node.js versions):
import data from "./data.json" with { type: "json" };Mixing CommonJS and ESM
If you have "type": "module" enabled but need one specific file to run as CommonJS, you can name that file with the .cjs extension.
.js → Follows the
package.json"type" field..mjs → Always ES Modules.
.cjs → Always CommonJS.