如何通过自动化测试验证package.json的types文件与模块实际导出匹配?
types field matches actual JS exports Great question—this is a super common pain point when maintaining TypeScript declarations alongside vanilla JavaScript code. Here are a few reliable ways to automate validation that your package.json types field points to a valid declaration file that matches your actual JS exports, preventing issues like broken imports after renaming files.
1. Use TypeScript's built-in --noEmit check
The simplest approach is to leverage TypeScript's own compiler to flag mismatches between your type declarations and JS code.
Steps:
- Ensure you have a
tsconfig.jsonin your project root with appropriate settings (adjust paths to match your project structure):{ "compilerOptions": { "allowJs": true, "checkJs": true, "noEmit": true, "skipLibCheck": true }, "include": ["src/**/*", "index.d.ts"], "exclude": ["node_modules"] } - Run the TypeScript compiler with no emit (we just want validation, not output files):
npx tsc --noEmit - If your
types-pointed.d.tsfile has declarations that don't match your JS exports (e.g., a renamed export that wasn't updated in types), TypeScript will throw clear errors like:error TS2305: Module '"."' has no exported member 'oldExportName'.
2. Use the tsd tool for dedicated type testing
For more granular, test-driven validation, use tsd—a tool built specifically for testing TypeScript type declarations.
Steps:
- Install
tsdas a dev dependency:npm install --save-dev tsd - Create a
test-ddirectory in your project root, and add a test file (e.g.,index.test-d.ts):import { myExport, anotherExport } from '../'; // Validate the type of an export expectType<string>(myExport); // Validate an export is a function with specific parameters/return type expectType<(input: number) => boolean>(anotherExport); // Test that invalid imports throw errors (e.g., if you removed an export) expectError(import('../').deletedExport); - Add a script to your
package.json:"scripts": { "test:types": "tsd" } - Run the type tests:
npm run test:types
This will fail immediately if your type declarations don't align with your actual JS exports, catching issues like outdated export names or mismatched types.
3. Integrate into CI/CD pipeline
To make sure this validation runs on every commit (so you never accidentally merge broken type declarations), add one of the above commands to your CI workflow. For example, in GitHub Actions:
jobs: type-check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 20 - run: npm install - run: npx tsc --noEmit - run: npm run test:types
All these methods will catch the exact issue you described—forgetting to update your type file after renaming a JS export—before it causes import failures for consumers of your package.
内容的提问来源于stack exchange,提问作者OliverRadini

