當嘗試將 PNG/SVG(或任何其他型別的影像!)匯入我的 React 專案時,TypeScript 會拋出以下錯誤:
TS2307: Cannot find module '../assets/images/homeHeroImage.svg' or its corresponding type declarations.
我在前端使用 react、typescript 和 webpack,檔案目錄結構如下:
frontend
src
assets
images
- homeHeroImage.svg
components
- App.tsx
- Header.tsx
home
- Home.tsx
- index.js
- global.d.ts
- package.json
- package-lock.json
- tsconfig.json
- webpack.config.js
下面是匯入錯誤的代碼(我可以使用@ts-ignore 抑制錯誤并且代碼有效):
import React from "react";
import Header from "../Header";
import HomeHeroImage from "../../assets/images/homeHeroImage.svg";
const Home = () => <Header headingText="Heading text" slogan="A slogan" imagePath={HomeHeroImage}/>;
export default Home;
我已經看到其他人發生此錯誤,并嘗試使用現有解決方案(例如這個),例如在包含以下內容的 src 檔案夾中添加一個 .d.ts 檔案(在我的情況下為 global.d.ts):
declare module "*.png";
declare module "*.svg";
declare module "*.jpg";
但是,這對我不起作用。以下是我的 tsconfig.json 檔案的內容供參考:
{
"compilerOptions": {
"target": "ES5",
"module": "ESNext",
"moduleResolution": "node",
"jsx": "react-jsx",
"noEmit": true,
"isolatedModules": true,
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"baseUrl": "frontend/src",
},
"files": ["frontend/src/*"],
"include": [
"frontend/src/*",
"frontend/src/global.d.ts",
]
}
任何想法將不勝感激。
uj5u.com熱心網友回復:
問題原來是我的 tsconfig.json 檔案中的一個設定(我不確定是哪一個,因為我只是用 create-react-app 配置的輸出替換了該檔案)。請參閱下面解決問題的新更新的 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"
},
"include": [
"frontend/src"
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492855.html
