Improve ESM compatibility#697
Conversation
There was a problem hiding this comment.
Im concerned here that the exports inclusion makes this breaking to a small number of users. I am always wary of packaging changes mid major (ala files, exports), as it can break things unless the paths cover everything that was possible previously.
There are indeed apps in the wild doing silly things like importing from lib which this change would break:
https://github.com/search?q=%22require%28%27body-parser%2F%22&type=code
(I think VSCode's auto-complete for imports often does these deep imports when there's no exports field, i've seen it a lot at a previous job. likely how folks ended up w/ this)
We can split out the index.js change as it's own PR, as that's standalone and won't break anyone. Or we can do an exhaustive exports field inside this same major. But that doesn't seem valuable here.
From the Node docs, we could do this to preserve back compat:
"exports": {
".": "./index.js",
"./package.json": "./package.json",
"./json": "./lib/types/json.js",
"./raw": "./lib/types/raw.js",
"./text": "./lib/types/text.js",
"./urlencoded": "./lib/types/urlencoded.js",
// Back compat entries start here
"./lib/*": "./lib/*.js", // will include read.js and utils.js, both internal but both still requireable today
"./lib/*.js": "./lib/*.js",
"./lib/types/*": "./lib/types/*.js",
"./lib/types/*.js": "./lib/types/*.js"
}047691b to
ce4040b
Compare
|
@jonchurch I totally agree we should provide these back compat entries until the next major. I pushed the changes please re-review. |
|
@jonchurch @bjohansebas Do we need a HISTORY.md entry? |
Yes, it’s a change that enables new things, so I’d say yes |
|
@bjohansebas Should we also document the subpath exports in |
|
Yes, also. |
Static exports allow Node.js cjs-module-lexer to detect named exports correctly, improving ESM interop and bundler behavior.
Add an exports field to package.json exposing json, raw, text,
and urlencoded parsers as subpath exports.
This allows consumers to import individual parsers directly:
- CommonJS: require('body-parser/json')
- ESM: import json from 'body-parser/json'
The change is fully backward compatible and enables users to
opt into loading only the parsers they need.
ce4040b to
9199b05
Compare
|
@bjohansebas Can you review the changes please? |
Ref: #666 (comment)
This PR contains 2 commits:
fix: use static exports instead of lazy getters
Static exports allow Node.js
cjs-module-lexerto detect namedexports correctly, improving ESM interop and bundler behavior.
feat: add subpath exports for individual parsers
Add an exports field to package.json exposing json, raw, text,
and urlencoded parsers as subpath exports.
This allows consumers to import individual parsers directly:
The change is fully backward compatible and enables users to
opt into loading only the parsers they need.
Closes #666