קובץ Typescript נותן שגיאה אם אינו כלול ב-tsconfig.json


יש לי את מבנה הקבצים הבא בפרויקט שלי:

- root
  - build
     - index.js
     - other files
  - src
     - index.ts
     - other files
  - postinstall.ts
  - tsconfig.json

אני רוצה לקמפל רק את הקבצים בתוך התיקייה src לתיקייה build ולא רוצה לקמפל את הקובץ postinstall.ts מכיוון שהוא משמש רק לאחר התקנת חבילה חדשה בפרויקט שלי.

אם אני לא מוסיף את postinstall.ts בתוך סעיף include ב-tsconfig.json אני רואה שגיאות כשאני פותח את הקובץ. הנה כמה שגיאות שקיבלתי:

Cannot find module 'fs' or its corresponding type declarations.ts(2307)
Cannot find module 'path' or its corresponding type declarations.ts(2307)
Cannot find name '__dirname'.ts(2304)

אם אני מוסיף אותו בקטע include אז כל השגיאות ב-postinstall.ts נעלמות אבל עכשיו יש לי את השגיאה 'rootDir' צפוי להכיל את כל קבצי המקור. ב-tsconfig.json.

הנה ההגדרות שלי של tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "rootDir": "./src",
    "removeComments": true,
    "typeRoots": [
      "./node_modules/@types",
      "./src/types"
    ],
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "sourceMap": true,
    "baseUrl": "./src",
    "paths": {
      "@/*": [
        "./*"
      ]
    },
    "outDir": "build",
    "experimentalDecorators": true,
    "strictPropertyInitialization": false
  },
  "tsc-alias": {
    "resolveFullPaths": true,
    "verbose": false
  },
  "compileOnSave": true,
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules"
  ]
}

איך אני יכול לפתור את זה? תודה

תשובה #1

אתה יכול להגדיר קובץ TS Config נוסף עבור postinstall.ts שאותו תוכל לקרוא tsconfig.node.json (כמו ש-Vite עושה עבור vite.config.ts שלהם):

{
  "compilerOptions": {
    "composite": true,
    "skipLibCheck": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true
  },
  "include": ["postinstall.ts"]
}

ואז אולי תשתמש בזה עם Typescript CLI עם הפקודה הבאה:

tsc --project tsconfig.node.json