網站搜尋

reactjs - 找不到模組 'file-name.png' 或其相應的型別宣告 - typescript react


我正在嘗試在我的 TypeScript React 專案中這樣導入一個 PNG:
import logo from 'assets/Logo.svg';

我收到這個 TS 錯誤:
找不到模組 'assets/Logo.svg' 或其對應的型別宣告.ts(2307)

有人知道這是為什麼嗎?我已在下面附上我的 tsconfig.json 文件,以防我配置錯誤了什麼:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "src"
  },
  "include": ["src"]
} 

答案#1

你的 src 資料夾中應該有一個 react-app-env.d.ts 檔案。
如果你沒有看到它,請在 src 資料夾中建立一個名為 react-app-env.d.ts 的新檔案。

現在,只需將以下程式碼加入你的 react-app-env.d.ts 檔案中。

declare module "*.png";
declare module "*.svg";
declare module "*.jpeg";
declare module "*.jpg";

你就可以開始了 :)