Main, Module, and Exports
You'll learn how to define multiple entry points in package.json so different consumers can load your package in the best way for their environment.
The Three Entry Point Fields
When you publish an npm package, you need to tell JavaScript runtimes where to start loading your code. Historically, the main field pointed to your CommonJS entry file (usually index.js). This worked fine when everyone used require().
But modern JavaScript supports ES modules (import/export), which bundlers can optimize better through tree shaking. The module field (a community convention) lets you specify a separate ES module entry point, so tools like Webpack or Rollup can use that version instead.
The Modern Approach: Exports
The exports field is the official, powerful successor. It lets you define conditional exports—different entry points based on how your package is being loaded:
{
"name": "my-package",
"version": "1.0.0",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
}
}
Here, "import" serves ES module consumers, while "require" serves CommonJS consumers. The exports field also prevents access to files you haven't explicitly exposed—it's your public API contract.
Why This Matters
Think of these fields as different doors into your package. main is the old front door everyone used. module is a side door for modern tools. exports is a sophisticated reception desk that routes visitors to the right department based on their needs.
Key Takeaway: Use main for backward compatibility, module for legacy bundler optimization, and exports for fine-grained control over how different environments load your package.