fix(javascript): fix types not being recognized for NodeNext module resolution #4540
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #4218
The problem was, since the
package.json
hastype: module
, Typescript is treating regulard.ts
files as module. But thed.ts
files are generated manually and they don't comply with how a module file should look like (e.g. missing file extensions on imports). So they are essentially more like CommonJS files.Luckily, there is a way to override the module detection. If the file has
cts
orcjs
extension, Typescript will treat that file as CommonJS. In this case, addingcts
extension only to theindex
file was enough.Ideally, the TS files should be built with
tsc
in the future to ensure the files comply with the corresponding module format.Also added a
files
field to the package.json so that only relevant files are included in the NPM bundle. Previously it also included files likespec
,src
, and dev config files, which made it confusing to debug.Tested my changes locally with various
moduleResolution
options likeNode, Node10, Node16, NodeNext, Bundler
and they work flawlessly. Only theClassic
option doesn't work but it also doesn't work on upstream and it doesn't work for most other packages as well.Alternative solutions
All of the other solutions require changes in more files but I will leave them here as an option.
The first obvious solution is to add extensions to all the TS files.
I checked various other packages like
lodash-es
and checked why they don't have this problem even though they don't have extension in TS files. Turns out, they don't havetype: module
in their package.json, so files are treated as CommonJS by default, even though the packages are ES packages.So one of the solutions is to remove
type: module
and convert alljs
files tomjs
.