tsconfig.json — Konfiguracja TypeScript
Strict mode, path aliases, project references, verbatimModuleSyntax i gotowe konfiguracje dla Next.js, Vite i Node.js.
6 kluczowych opcji tsconfig
strict, noUncheckedIndexedAccess, moduleResolution, verbatimModuleSyntax, paths i exactOptionalPropertyTypes — zalecenia i efekty.
| Opcja | Opis | Zalecane | Efekt |
|---|---|---|---|
| strict: true | Włącza 8 strict opcji | Zawsze (all projects) | Bezpieczne typy, mniej błędów runtime |
| noUncheckedIndexedAccess | array[i] może być undefined | Tak (new projects) | Wymusza sprawdzanie tablic |
| moduleResolution: bundler | Dla Vite/webpack (TS 5+) | Tak (dla bundled apps) | Poprawne resolving z bundlerami |
| verbatimModuleSyntax | Wymusza import type | Tak (TS 5+) | Czyste type-only imports |
| paths: {'@/*': [...]} | Path aliases dla importów | Tak (dla wygody) | Czystsze importy, brak ../../../ |
| exactOptionalPropertyTypes | Ścisłe optional properties | Dla strict projects | Rozróżnienie undefined vs brak klucza |
Często zadawane pytania
Co to jest tsconfig.json i jakie opcje są najważniejsze?
tsconfig.json: konfiguracja TypeScript compiler (tsc). Określa: jakie pliki kompilować. Jak kompilować. Target JavaScript. Sprawdzanie typów. Podstawowe opcje compilerOptions: target: 'ES2022' — docelowa wersja JS. module: 'ESNext' lub 'CommonJS'. moduleResolution: 'bundler' (TS 5+) lub 'node16'. lib: ['ES2022', 'DOM', 'DOM.Iterable'] — dostępne typy. outDir: './dist' — katalog wyjściowy. rootDir: './src' — katalog źródłowy. strict: true — ZAWSZE włącz (włącza 8 opcji). declaration: true — generuj .d.ts. declarationMap: true — source maps dla declaration. sourceMap: true — source maps dla JS. esModuleInterop: true — import defaultowy z CommonJS. allowSyntheticDefaultImports: true. forceConsistentCasingInFileNames: true. Strict mode włącza: strictNullChecks. strictFunctionTypes. strictBindCallApply. strictPropertyInitialization. noImplicitAny. noImplicitThis. alwaysStrict. useUnknownInCatchVariables (TS 4.4+). Dodatkowe strict opcje (extra): noUncheckedIndexedAccess — tablice mogą być undefined. noImplicitReturns — wszystkie ścieżki muszą returnować. noFallthroughCasesInSwitch. exactOptionalPropertyTypes — {} nie spełnia {a?: string}. Pliki: include: ['src/**/*']. exclude: ['node_modules', 'dist']. files: ['src/index.ts'] — explicit file list.
TypeScript path aliases — jak konfigurować @/components i @/utils?
Problem: import '../../../components/Button' — brzydkie. Rozwiązanie: paths aliasy. paths in tsconfig.json: 'paths': {'@/*': ['./src/*'], '@components/*': ['./src/components/*'], '@utils/*': ['./src/utils/*']}. baseUrl: '.' — wymagane dla paths. Teraz: import {Button} from '@/components/Button'. Import {formatDate} from '@/utils/date'. Aliasy: @ — popularny prefix. ~ — alternatywny. Waga: tsconfig paths to tylko dla type checking! Bundler musi być skonfigurowany osobno. Vite aliasy: import path from 'path'. resolve: {alias: {'@': path.resolve(__dirname, './src')}}. Lub: import {fileURLToPath} from 'url'. const __dirname = fileURLToPath(new URL('.', import.meta.url)). '@': path.resolve(__dirname, 'src'). Next.js: automatycznie z tsconfig.json paths. Brak dodatkowej konfiguracji. Jest: moduleNameMapper: {'^@/(.*)$': '/src/$1'}. Webpack: alias: {'@': path.resolve(__dirname, 'src')}. tsconfig-paths: dla ts-node. require('tsconfig-paths/register'). tsx: tsconfig-paths wbudowane. Validacja: tsc --noEmit sprawdź tylko typy. Pomocnicze package: @types/node dla Node.js types. Absolute vs relative: preferuj aliasy dla cross-module imports. Relative dla blisko powiązanych plików (ten sam feature/moduł). Barrel exports: index.ts w każdym katalogu. export {Button} from './Button'. Wygodne ale może powodować circular deps.
TypeScript Project References — podział na subprojekty?
Project References (TS 3.0+): podział TypeScript projektu na podprojekty. Każdy ma własne tsconfig.json. composite: true — enable project references. declaration: true — wymagane. Incremental builds — tylko zmienione subprojekty. Monorepo zastosowanie: packages/ui/tsconfig.json: composite: true. packages/api/tsconfig.json: references: [{path: '../ui'}]. root tsconfig.json: references: [{path: './packages/ui'}, {path: './packages/api'}]. tsc --build lub tsc -b — buduje w kolejności. Caching: tsbuildinfo — TypeScript cache. Buduje tylko gdy zmiany. Znacznie szybszy dla dużych projektów. Nx i Turborepo: konfigurują project references automatycznie. tsconfig.base.json pattern: root tsconfig z wspólnymi ustawieniami. Każdy package extends: {extends: '../../tsconfig.base.json', compilerOptions: {...}}. Typowe problemy: circular dependencies między packages. Rozwiązanie: interface-first (osobny package). Strict project boundaries. @typescript-eslint/no-restricted-imports. Verbatim Module Syntax (TS 5.0): 'verbatimModuleSyntax': true. Wymuszaj import type dla type-only imports. Eliminuje emisję pustych import statements. Erasable Syntax (TS 5.4): --erasableSyntaxOnly. Usuwaj tylko type annotations. Kompatybilny z Node.js strip-types. TypeScript isolatedModules: każdy plik niezależny. Wymagane dla Babel/esbuild transpilation. Zapobiega const enum i namespace merging.
TypeScript strict mode — noImplicitAny, strictNullChecks i inne?
strictNullChecks: null i undefined nie są typem wszystkiego. Bez strict: function greet(name: string) {return name.toUpperCase()} // greet(null) = crash. Ze strict: TypeScript error przy greet(null). string | null | undefined — explicit. Optional chaining: user?.address?.city. Nullish coalescing: value ?? 'default'. noImplicitAny: brak niejawnego any. Musisz jawnie deklarować typy. Parametry funkcji muszą mieć typy. Wyjątek: kontekstowe typy (callback). strictFunctionTypes: function types są contra-variant. Ogranicza niekompatybilne funkcje w assignmentach. strictPropertyInitialization: wszystkie class properties muszą być zainicjowane w konstruktorze. Or: definite assignment: name!: string. Or: declare: memoizedValue?: string. noUncheckedIndexedAccess: array[0] zwraca T | undefined. Wymusza sprawdzenie przed użyciem. const first = arr[0]. if (first !== undefined) console.log(first). useUnknownInCatchVariables: error w catch jest unknown nie any. Wymusza type narrowing. try {} catch (err) {if (err instanceof Error) console.log(err.message)}. noImplicitReturns: wszystkie ścieżki muszą returnować wartość. Unika undefined z powodu missing return. exactOptionalPropertyTypes: {name?: string} !== {name: string | undefined}. Ścisłe rozróżnienie między brak klucza a undefined. Dla nowych projektów: włącz wszystkie strict opcje. Dla migracji: stopniowo. strict: true jako start. Potem dodawaj noUncheckedIndexedAccess, noImplicitReturns. TypeScript error ignore: @ts-ignore (unikaj). @ts-expect-error (preferred — błąd gdy brak error). @ts-nocheck — wyłącz dla całego pliku.
tsconfig dla Next.js, Vite i Node.js — różne konfiguracje?
Next.js tsconfig: automatycznie generowany przez create-next-app. target: 'ES2017'. lib: ['dom', 'dom.iterable', 'esnext']. allowJs: true. skipLibCheck: true. strict: true. noEmit: true (Next.js kompiluje inaczej). incremental: true. module: 'esnext'. moduleResolution: 'bundler'. jsx: 'preserve'. plugins: [{name: 'next'}]. paths: {'@/*': ['./src/*']}. Vite + React tsconfig: dwa pliki: tsconfig.json (aplikacja) + tsconfig.node.json (vite.config.ts). tsconfig.json: target ES2020, lib ES2020+DOM, module: ESNext, moduleResolution: bundler, jsx: react-jsx, strict: true. tsconfig.node.json: composite: true, target: ES2022, module: ESNext, moduleResolution: bundler, allowSyntheticDefaultImports: true. Node.js (backend) tsconfig: target: 'ES2022' lub 'ES2023'. module: 'NodeNext'. moduleResolution: 'NodeNext'. lib: ['ES2022']. types: ['node']. outDir: './dist'. rootDir: './src'. strict: true. sourceMap: true. Declaration files: declaration: true dla publishowanych packages. declarationMap: true dla debugging. Wspólny tsconfig.base.json: compilerOptions ogólne. Packages extends i override. esm vs cjs: module: 'ESNext' + moduleResolution: 'bundler' dla bundled. module: 'NodeNext' + type: 'module' dla native ESM Node.js. ts-node config: ts-node: {esm: true, experimentalSpecifierResolution: 'node'} w tsconfig. tsx: brak konfiguracji. Szybszy niż ts-node (esbuild-based). Bun: TypeScript native bez config.
Powiązane artykuły
Skontaktuj się z nami
Porozmawiajmy o Twoim projekcie. Bezpłatna wycena w ciągu 24 godzin.
Wyślij zapytanie
Telefon
+48 790 814 814
Pon-Pt: 9:00 - 18:00
adam@fotz.pl
Odpowiadamy w ciągu 24h
Adres
Plac Wolności 16
61-739 Poznań
Godziny pracy
Wolisz porozmawiać?
Zadzwoń teraz i porozmawiaj z naszym specjalistą o Twoim projekcie.
Zadzwoń teraz