首頁
學習紀錄
遊戲心得影視Life書單案件檔案
Side Projects委託作品與二創互動實驗場
Kurau
百百 BLOG
首頁
學習紀錄
遊戲心得影視Life書單案件檔案
Side Projects委託作品與二創互動實驗場
Kurau

Kurau Blog

「隨心而寫,真真假假,都是我」

一個記錄生活、輸出興趣的個人空間。
遊戲、影視、閱讀、學習……每一段體驗都值得留下文字。

頁面導覽

  • 學習紀錄
  • 遊戲心得
  • 影視Life
  • 書單
  • 委託作品與二創
  • Kurau
  • 合作邀請

找到我

歡迎來 Discord 找我聊天!

“曾經發生的事不可能忘記,只是暫時想不起來而已。”-《神隱少女》

© 2026 Kurau All rights reserved

前端框架

react-app-env.d.ts

By Kurau·2023-03-23·Updated 2026-05-09·3 分鐘閱讀

react-app-env.d.ts 是什麼

TL;DR
CRA(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" />
typescript

那個 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;
}
// ... 等等
typescript

沒這個檔會怎樣

如果你不小心把它刪了 / 沒生成,結果是:

import logo from './logo.png';  // ❌ TS error: Cannot find module
typescript
修復方式
在 src/ 建立 react-app-env.d.ts 寫一行就好:
/// <reference types="react-scripts" />
typescript

然後重啟 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
typescript

這樣 process.env.REACT_APP_API_URL 就會有自動補全 + 型別檢查。


各框架的等效機制

框架對應檔你需要做的事
CRAsrc/react-app-env.d.ts別刪它
Next.jsnext-env.d.ts別動它(每次 next dev 會重生)
Vitesrc/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
bash

這兩個都不需要 react-app-env.d.ts,各自有更乾淨的 ambient types 機制。

目錄

    ◆ 相關文章

    • HTML React 打字機效果

      2026-05-09
    • Framer Motion 打造比最棒還要棒的動畫

      2026-05-09
    • Redux

      2026-05-09
    • React-Use套件

      2026-05-09
    ← 上一篇Redux下一篇 →React-Router-Dom V6 Anchor Link

    ◆ 關於作者

    Kurau

    個人寫作 / 創作的 SoT,記錄遊戲、影視、學習與生活。

    更多 Kurau 的文章