This strategy is similar to extensionless
, but uses directories with package.json stubs that redirect to another file via main
(and types
) instead of requiring that the implementation (and types) files actually be at the file-system-apparent location.
import "package-json-redirects/one";
An exports
-supporting resolver will look up "./one"
in the package.json exports
, which in turn points either to ./cjs/one.js
or ./esm/one.js
, depending on the conditions presented by the resolver. A non-exports
-supporting resolver will instead find ./one/package.json
:
{
"main": "../cjs/one.js",
"types": "../types/one.d.ts"
}
And reroute accordingly. The package.json stub chooses to route the non-exports
-supporting resolver to the CommonJS files, since Node 11 does not support ESM-format files.
Note that the separate handling of ESM and CJS, as well as the decision to present a unified set of types for the two, is orthogonal to the subpath exports demonstration. (Including separate types for CJS and ESM files, as extensionless
does, is often a better choice, and is compatible with this strategy.)
Pros:
- Well-supported
- Supports putting implementation and types files in subfolders
- Can model subpaths that map to a file with a different name than the subpath
Cons:
- Lots of files and folders (aesthetic)
- Need to add more every time a new subpath is added
- Cannot support
*
wildcards; need to create apackage.json
for all possible matches