react-app-env.d.ts
react-app-env.d.ts 是什麼
TL;DRCRA(Create React App)專用的 TypeScript ambient type 宣告檔,告訴 TS「你可以 import 圖片、CSS、SVG 這些非 JS 檔」。2026 年用 Next.js / Vite 都不需要這個檔(它們各自有自己的 ambient types)。
為什麼會有這個檔
純 TypeScript 只認得 .ts / .tsx / .js,看到 import logo from './logo.png' 會直接報錯:
Cannot find module './logo.png' or its corresponding type declarations.
CRA 用 Webpack 把圖片當作模組處理,所以需要一份 ambient declaration 告訴 TS「這些 import 是合法的、回傳值是 string」:
// react-app-env.d.ts(CRA 自動產生)
/// <reference types="react-scripts" />
那個 react-scripts 內建的 type definitions 包含:
declare module '*.png' { const src: string; export default src; }
declare module '*.svg' { const content: string; export default content; }
declare module '*.module.css' {
const classes: { readonly [key: string]: string };
export default classes;
}
// ... 等等
沒這個檔會怎樣
如果你不小心把它刪了 / 沒生成,結果是:
import logo from './logo.png'; // ❌ TS error: Cannot find module
修復方式在 src/ 建立 react-app-env.d.ts 寫一行就好:/// <reference types="react-scripts" />然後重啟 dev server。
自訂 ambient types
如果你要 擴充自己的全域型別(例如自訂環境變數),可以加進這個檔:
/// <reference types="react-scripts" />
declare global {
namespace NodeJS {
interface ProcessEnv {
readonly REACT_APP_API_URL: string;
readonly REACT_APP_GA_ID: string;
}
}
}
export {}; // 讓檔案被當成 module
這樣 process.env.REACT_APP_API_URL 就會有自動補全 + 型別檢查。
各框架的等效機制
| 框架 | 對應檔 | 你需要做的事 |
|---|---|---|
| CRA | src/react-app-env.d.ts | 別刪它 |
| Next.js | next-env.d.ts | 別動它(每次 next dev 會重生) |
| Vite | src/vite-env.d.ts | 自訂時改它 |
| 自建 Webpack | 自己寫 *.d.ts | 全手動 |
Next.js 注意next-env.d.ts 文件頂頭就寫「Do not edit」,因為 next build 會覆寫它。要擴充自己的型別請另開 additional.d.ts 或 types/ 資料夾。
2026 年的建議:離開 CRA
CRA 已被 React 官方移除推薦(2025-02 起官網不再列 CRA,改推 Vite / Next.js / Remix)。新專案直接用:
# Vite + React + TS
npm create vite@latest my-app -- --template react-ts
# 或 Next.js
npx create-next-app@latest my-app --typescript
這兩個都不需要 react-app-env.d.ts,各自有更乾淨的 ambient types 機制。