Package.json Type Field
You'll learn how to use the type field in package.json to tell Node.js which module system to use by default.
What This Field Does
Think of the type field as a building-wide policy: it sets the default "language" your entire project speaks. Without it, Node.js assumes .js files are CommonJS. By setting type, you declare whether .js files should be treated as ESM or CJS.
The Two Values
In your package.json, you can specify:
{
"type": "module"
}
This tells Node.js: "Treat all .js files as ES Modules by default." Now import and export work without needing the .mjs extension.
Alternatively:
{
"type": "commonjs"
}
This explicitly sets CommonJS as the default (which is already Node.js's default behavior if you omit type entirely). Your .js files will expect require() and module.exports.
Why It Matters
Before this field, mixing module systems required awkward file extensions (.mjs for ESM, .cjs for CJS). The type field lets you pick your project's primary module system and stick with standard .js files.
If you set "type": "module" but need one CommonJS file, just name it .cjs. The opposite works too: in a CommonJS project, use .mjs for ESM files.
Practical Impact
This setting affects how Node.js interprets your code before running it. Choose based on your project's needs: modern projects typically use "type": "module" to embrace ESM, while legacy codebases stick with "commonjs".
Key Takeaway: The type field in package.json controls whether .js files default to ESM ("module") or CommonJS ("commonjs"), eliminating the need for special file extensions in most cases.