为何ts-node无法识别自定义类型声明文件,而tsc与Webstorm可正常识别?
Great question—this is a common gotcha when working with ts-node in ESM mode. Let’s break down why this happens and how to fix it.
Why the Discrepancy?
First, let’s clarify why tsc and WebStorm work fine while ts-node throws an error:
- tsc: Strictly follows your
tsconfig.jsonrules. Yourinclude: ["./src/**/*"]wildcard correctly picks upsrc/types/custom.d.ts, andtypeRootstells it to look in that directory for custom types. - WebStorm: Its built-in TypeScript service scans all
.d.tsfiles in your project (unless explicitly excluded), so it automatically finds your declaration regardless of minor config quirks. - ts-node (ESM mode): When running with ES modules enabled (via
"ts-node": { "esm": true }and--experimental-specifier-resolution=node), ts-node’s type resolution logic has subtle differences from tsc. It may not automatically load all included.d.tsfiles by default, or might prioritize different lookup paths.
Fixes to Try (Ordered by Simplicity)
1. Add the --files Flag to Your ts-node Command
ts-node doesn’t load all included files by default in ESM mode. Adding the --files flag forces it to process every file specified in your include array, including your custom type declaration:
NODE_OPTIONS='--experimental-specifier-resolution=node' npx ts-node --files -P tsconfig.json src/index.ts
2. Explicitly Include Your custom.d.ts in tsconfig.json
While ./src/**/* should match your type file, sometimes ts-node’s ESM parser doesn’t resolve the wildcard as expected. Try adding the file path directly to your include array:
{ "include": [ "./src/**/*", "./src/types/custom.d.ts", "jest.config.js" ] }
3. Restructure Your Type Declarations to Match @types Convention
ts-node tends to prioritize the standard @types directory structure. Create a src/@types/mongo-uri-tool/index.d.ts file with your declaration:
declare module 'mongo-uri-tool';
Since your typeRoots includes src/types, renaming the directory to @types (under src) aligns with TypeScript’s default type lookup behavior, which ts-node handles more reliably.
4. Update ts-node to the Latest Version
Older versions of ts-node had bugs in ESM type resolution. Run this to upgrade:
npm install --save-dev ts-node@latest
Verify the Fix
After trying any of these solutions, re-run your ts-node command— the TS7016 error should disappear, and ts-node will recognize your custom module declaration just like tsc and WebStorm do.
内容的提问来源于stack exchange,提问作者Paymahn Moghadasian

