我正在嘗試添加typescript到我的專案中并使用打字稿撰寫新組件。我按照檔案進行操作,但出現此錯誤:
can't resolve [the typescript file]
即使有一個新create-react-app專案也會發生這種情況。
根據CRA 檔案添加typescript到現有的 Create React App 專案,首先,我們必須安裝typescript和type definition files:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
快完成了!
將js/jsx檔案重命名為tsx并重新啟動您的開發服務器!
為簡單起見,我正在創建一個typescript名為的檔案test.tsx,其中包含該Test組件:
export default function Test(){
return (
<div>this is test to see typescirpt</div>
)
}
并將其匯入main.js并渲染:
import Test from "./test";
function App() {
return (
<div className="App">
<Test />
</div>
);
}
export default App;
現在我正在重新啟動開發服務器(我用 關閉了前一個CRTL c)npm start。
我收到了這個錯誤:
Compiled with problems:
ERROR in ./src/App.js 4:0-26
Module not found: Error: Can't resolve './test' in '/home/g/w/ts/test_adding_ts/src'
我使用了一個新create-react-app專案,遵循了檔案,并看到了這個錯誤。(為什么?)
這是我安裝的依賴項:
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.0.1",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.4.1",
"@types/node": "^17.0.24",
"@types/react": "^18.0.5",
"@types/react-dom": "^18.0.1",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "5.0.1",
"typescript": "^4.6.3",
"web-vitals": "^2.1.4"
},
編輯:
這些答案都不是我想要的。我認為世界已經改變,現在 Reddit 是尋求幫助的更好地方。
uj5u.com熱心網友回復:
您是否在根目錄中創建了組態檔:tsconfig.json?我沒有看到問題中提到了這一點。
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": [
"src"
]
}
如果沒有創建,你可以在 package.json 旁邊的根目錄中創建一個并粘貼上面的配置。或者已經創建,您可以通過上述配置替換現有配置并重新檢查。
uj5u.com熱心網友回復:
如果按照原樣執行每個步驟,CRA 檔案指南就可以作業,但是在說“將任何檔案重命名為 TypeScript 檔案”時非常棘手。根據使用 typescript 的源代碼,您的應用程式應包含檔案。create-react-app ./tsconfig.json
如指南中所述,簡單重命名僅適用于./src/index.(js|ts|jsx|tsx)檔案,但只要create-react-app 配置 webpack排除所有打字稿檔案,所有匯入都將失敗。
最小./tsconfig.json的檔案,正如我個人檢查的 CRA 版本 5.0.1 是以下一個:
{
"compilerOptions": {
"esModuleInterop": true,
"jsx": "react"
}
}
uj5u.com熱心網友回復:
正如bnays mhz所說,您必須在根目錄中創建一個tsconfig.json并添加他提供的相同內容,您還必須將所有.js檔案重命名為.tsx,它將編譯您的應用程式,其中包含您必須手動解決的型別錯誤。
但我建議您不要這樣做,而是使用typescript模板。
npx create-react-app my-app --template typescript
它將為您配置一切,您可以輕松開始。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/464206.html
