In this lesson, you will learn how to use the type field in your package.json to tell Node.js exactly how to interpret your JavaScript files: as CommonJS (CJS) or ECMAScript Modules (ESM).
Defining the Module System
As we discussed in previous lessons, Node.js supports two distinct module systems: the legacy CommonJS (using require) and the modern ESM (using import/export). Because these systems behave differently—ESM is asynchronous by nature while CJS is synchronous—Node.js needs a clear instruction on how to treat the files in your project.
This is where "Module Governance" via package.json comes into play. By adding a type property, you act as the architect of your project’s environment.
Setting the type
By default, Node.js treats files ending in .js as CommonJS. If you want your entire project to use the modern ESM syntax by default, you simply add "type": "module" to your package.json:
{
"name": "my-awesome-project",
"version": "1.0.0",
"type": "module"
}
Once this is set, any .js file in your folder will be treated as an ESM module. You can now use import and export statements without needing to rename your files to .mjs.
Why this matters
Think of package.json as the "rulebook" for your application. When Node.js encounters your code, it checks this file first to resolve how the module loading algorithm should behave. If you omit the type field, Node.js defaults to CommonJS. Explicitly setting this field prevents confusion and runtime errors, ensuring that the runtime knows exactly which syntax to expect when it parses your code.
If you ever need to mix systems—for example, if you set your project to ESM but occasionally need a legacy CJS file—you can explicitly name that specific file with a .cjs extension, which will override the package.json rule. Governance is all about consistency, and this field is your primary tool to enforce it.
Key Takeaway: The type field in package.json explicitly defines whether your project defaults to ESM or CommonJS, providing the ground rules for how Node.js interprets and loads your modules.