iti
iti copied to clipboard
Type resolution fails when importing iti with "moduleResolution": "NodeNext"
Problem Description
When using iti in a TypeScript project with "moduleResolution": "NodeNext"
in your tsconfig.json
, type information for iti cannot be located.
This line:
import { createContainer } from 'iti'
Produces the error:
Could not find a declaration file for module 'iti'. '<project path>/node_modules/iti/dist/iti.modern.js'
implicitly has an 'any' type.
Try `npm i --save-dev @types/iti` if it exists or add a new declaration (.d.ts) file
containing `declare module 'iti';`
The project will still compile and run with tsc
; you just don't have type information for iti for static checking, linting, etc.
Cause
There are two causes:
-
The
exports
map in iti'spackage.json
contains anexports
map, but thetypes
key is not defined for each export. See this TypeScript issue for a complete explanation. Whenexports
is defined, top-leveltypes
ortypings
keys are ignored. -
The
export ... from
statements initi/src/index.ts
need to use an explicit.js
extension. Without this,import { createContainer } from 'iti'
will nominally succeed, but the type ofcreateContainer
will just beimport
, and the static analysis gets very confused.
Proposed fix
-
The first issue is simple: just add
"types": "./dist/src/index.d.ts"
to theexports
map inpackage.json
. -
For the second issue, I'll be honest: I'm fairly new to JS/TS. My understanding is that explicit
.js
extensions are required for import/export statements when using ESM ("type": "module"
inpackage.json
). So I'm not sure how iti is getting away with "bare" imports in the first place. But in any case, adding extensions only to theexport
statements insrc/index.ts
is enough to satisfy the consumer's linter and should be backwards-compatible with CJS. With that said, two of the iti tests (dispose....
) try toimport { createContainer } from '../src'
, which needs to be../src/iti
after this change. The other tests already import this way.
I have a fork with these proposed changes made to iti
and iti-react
. I can make a PR if you'd like.
Oh great! Thank you @tmillican for opening this up! Will check it and merge into the upstream 🙇♂️
Also, this is a great description, I've learned something new :)
@molszanski thoughts on getting this fix added?
@danielmahon oh! Yeah, forgot about it! Will release a minor with better cjs/mjs compatibility!