What does the main field in package.json do?
main names the entry file that Node loads when someone requires or imports your package by name. If it is missing, Node falls back to index.js. Modern packages may also use the exports field.
Explain it simply
When you write require("fest-utils"), Node finds the folder node_modules/fest-utils and then asks, "Which file is the front door?" The main field is the answer. It is like the signboard at a college gate that tells visitors which building to enter first.
Example
{
"name": "fest-utils",
"version": "2.0.0",
"main": "lib/index.js"
}With this, require("fest-utils") loads lib/index.js. If main is absent, Node tries index.js at the package root.
Two related points:
- For an application you run yourself,
mainmatters little. You usually start it withnode src/server.jsor an npm script. - The newer
exportsfield gives more control: it can point to different files forrequireandimport, and it blocks deep imports likefest-utils/lib/secret.jsthat you did not intend to publish. Whenexportsexists, it takes priority overmain.
{
"exports": {
".": { "import": "./esm/index.js", "require": "./cjs/index.cjs" }
}
}What to say in the interview
"main is the entry point used when the package is required by name, defaulting to index.js. exports is the modern replacement that supports separate ESM and CJS entries and hides internal files."
Common mistakes
- Pointing
mainat a file that is not included in the published package. - Forgetting that
exportsoverridesmain.