React和打字稿的兩種很棒的技術。知道如何做事會變得棘手,有時很難找到正確的答案。不用擔心。我們匯總了最佳實踐以及示例,以澄清您可能存在的任何疑問。
>讓我們潛入!鑰匙要點
> TS:“嘿,這是您所有的UI代碼嗎?” 反應:“是的!”
TS:“酷!我要編譯它,並確保您什麼都沒有錯過。 反應:“對我來說聽起來不錯!”
所以答案是肯定的,它確實如此!但是後來,當我們涵蓋TSCONFIG.JSON設置時,大多數時候您都需要使用“ Noemit”:true。這意味著Typescript在編譯後不會發出JavaScript。這是因為通常,我們只是利用TypeScript進行類型檢查。
>在CRA設置中,通過反應標記處理輸出。我們運行紗線構建和反應 - 訂閱將產量捆綁為生產。
> Typescript可以與React和WebPack一起使用?
是的,Typescript可以與React和WebPack一起使用。幸運的是,WebPack文檔有一個指南。最佳實踐
>我們已經研究了最常見的問題,並彙總了與Typescript有關的最常見用例中的這份方便的列表。這樣,您可以將本文用作自己項目中的參考。
>最不有趣,但最重要的部分是配置。我們如何在最短的時間內設置一切,以提供最大的效率和生產力?我們將討論項目設置,包括:
> eslint
>這將使您的最低限度開始用打字稿寫作。一些明顯的差異是:
.tsx文件擴展
npx create-react-app my-app <span>--template typescript </span>> tsconfig.json
react-app-env.d.ts
其他建議來自React-Typecript-Cheatsheet社區,解釋來自官方打字稿手冊中的編譯器選項文檔。如果您想了解其他選擇及其所做的事情,這是一個很棒的資源。
> eslint/Prettier為了確保您的代碼遵循項目或團隊的規則,風格是一致的,建議您設置Eslint且更漂亮。為了讓他們效果很好,請按照以下步驟設置。
npx create-react-app my-app <span>--template typescript </span>
<span>{ </span> <span>"compilerOptions": { </span> <span>"target": "es5", // Specify ECMAScript target version </span> <span>"lib": [ </span> <span>"dom", </span> <span>"dom.iterable", </span> <span>"esnext" </span> <span>], // List of library files to be included in the compilation </span> <span>"allowJs": true, // Allow JavaScript files to be compiled </span> <span>"skipLibCheck": true, // Skip type checking of all declaration files </span> <span>"esModuleInterop": true, // Disables namespace imports (import * as fs from "fs") and enables CJS/AMD/UMD style imports (import fs from "fs") </span> <span>"allowSyntheticDefaultImports": true, // Allow default imports from modules with no default export </span> <span>"strict": true, // Enable all strict type checking options </span> <span>"forceConsistentCasingInFileNames": true, // Disallow inconsistently-cased references to the same file. </span> <span>"module": "esnext", // Specify module code generation </span> <span>"moduleResolution": "node", // Resolve modules using Node.js style </span> <span>"isolatedModules": true, // Unconditionally emit imports for unresolved files </span> <span>"resolveJsonModule": true, // Include modules imported with .json extension </span> <span>"noEmit": true, // Do not emit output (meaning do not compile code, only perform type checking) </span> <span>"jsx": "react", // Support JSX in .tsx files </span> <span>"sourceMap": true, // Generate corrresponding .map file </span> <span>"declaration": true, // Generate corresponding .d.ts file </span> <span>"noUnusedLocals": true, // Report errors on unused locals </span> <span>"noUnusedParameters": true, // Report errors on unused parameters </span> <span>"incremental": true, // Enable incremental compilation by reading/writing information from prior compilations to a file on disk </span> <span>"noFallthroughCasesInSwitch": true // Report errors for fallthrough cases in switch statement </span> <span>}, </span> <span>"include": [ </span> <span>"src/**/*" // *** The files TypeScript should type check *** </span> <span>], </span> <span>"exclude": ["node_modules", "build"] // *** The files to not type check *** </span><span>} </span>
<span>yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react --dev </span>
module<span>.exports = { </span> <span>parser: '@typescript-eslint/parser', // Specifies the ESLint parser </span> <span>extends: [ </span> <span>'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react </span> <span>'plugin:@typescript-eslint/recommended', // Uses the recommended rules from @typescript-eslint/eslint-plugin </span> <span>], </span> <span>parserOptions: { </span> <span>ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features </span> <span>sourceType: 'module', // Allows for the use of imports </span> <span>ecmaFeatures: { </span> <span>jsx: true, // Allows for the parsing of JSX </span> <span>}, </span> <span>}, </span> <span>rules: { </span> <span>// Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs </span> <span>// e.g. "@typescript-eslint/explicit-function-return-type": "off", </span> <span>}, </span> <span>settings: { </span> <span>react: { </span> <span>version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use </span> <span>}, </span> <span>}, </span><span>}; </span>
<span>yarn add prettier eslint-config-prettier eslint-plugin-prettier --dev </span>
>
vs代碼擴展和設置我們添加了Eslint和Prettier,下一步改進我們的DX是自動修復/將我們的代碼固定在保存上。
首先,安裝ESLINT擴展程序和VS代碼的更漂亮的擴展名。這將使Eslint與您的編輯器無縫集成。
>
接下來,通過將以下內容添加到您的.vscode/settings.json:>保存時,這將允許VS代碼工作魔術並修復您的代碼。它很漂亮!
module<span>.exports = { </span> <span>semi: true, </span> <span>trailingComma: 'all', </span> <span>singleQuote: true, </span> <span>printWidth: 120, </span> <span>tabWidth: 4, </span><span>}; </span>
這些建議還來自先前鏈接的文章“在打字稿項目中使用Eslint和Prettier”,作者:
。>
注意:要閱讀有關React.fc的更多信息,請在此處查看,然後在此處閱讀React.Reactnode。組件 > React的核心概念之一是組件。在這裡,我們將提到標準組件作為React V16.8,這意味著使用鉤子而不是類。 總體而言,基本組件有很多關注。讓我們看一個示例:
函數聲明
。我們用react.node註釋,因為它是返回的。相比之下,第二個示例使用
函數表達式。module<span>.exports = { </span> <span>parser: '@typescript-eslint/parser', // Specifies the ESLint parser </span> <span>extends: [ </span> <span>'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react </span> <span>'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin </span><span>+ 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier </span><span>+ 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. </span> <span>], </span> <span>parserOptions: { </span> <span>ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features </span> <span>sourceType: 'module', // Allows for the use of imports </span> <span>ecmaFeatures: { </span> <span>jsx: true, // Allows for the parsing of JSX </span> <span>}, </span> <span>}, </span> <span>rules: { </span> <span>// Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs </span> <span>// e.g. "@typescript-eslint/explicit-function-return-type": "off", </span> <span>}, </span> <span>settings: { </span> <span>react: { </span> <span>version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use </span> <span>}, </span> <span>}, </span><span>}; </span>,因為第二個實例返回函數,而不是值或表達式,我們用react.fc進行了
函數類型的註釋。功能組件”。 記住兩者可能會令人困惑。這主要是設計選擇的問題。無論您選擇哪個在項目中使用,都可以始終如一地使用。 > props 我們將介紹的下一個核心概念是道具。您可以使用接口或類型定義道具。讓我們看看另一個示例:
在類型或接口方面,我們建議按照React-Typecript-Cheatsheet社區提出的準則:>
>
在此組件中,我們為我們的道具使用類型。每個道具都有上面列出的簡短描述,可以為其他開發人員提供更多上下文。這 ?在命名顏色的道具之後,表明它是可選的。兒童道具會採取反應。回答節點,因為它接受了組件的有效返回值的所有內容(在此處閱讀更多)。為了說明我們的可選顏色道具,我們在破壞它時會使用默認值。此示例應涵蓋基礎知識,並表明您必須為道具編寫類型,並同時使用可選的和默認值。
一般而言,在React和TypeScript項目中編寫道具時,請記住這些事情:
npx create-react-app my-app <span>--template typescript </span>始終使用tsdoc符號 /** 評論* /。
始終向您的道具添加描述性評論
無論您是為組件道具使用類型還是接口,都可以始終如一地使用它們。 當道具是可選的,適當處理或使用默認值時。鉤子
<span>{ </span> <span>"compilerOptions": { </span> <span>"target": "es5", // Specify ECMAScript target version </span> <span>"lib": [ </span> <span>"dom", </span> <span>"dom.iterable", </span> <span>"esnext" </span> <span>], // List of library files to be included in the compilation </span> <span>"allowJs": true, // Allow JavaScript files to be compiled </span> <span>"skipLibCheck": true, // Skip type checking of all declaration files </span> <span>"esModuleInterop": true, // Disables namespace imports (import * as fs from "fs") and enables CJS/AMD/UMD style imports (import fs from "fs") </span> <span>"allowSyntheticDefaultImports": true, // Allow default imports from modules with no default export </span> <span>"strict": true, // Enable all strict type checking options </span> <span>"forceConsistentCasingInFileNames": true, // Disallow inconsistently-cased references to the same file. </span> <span>"module": "esnext", // Specify module code generation </span> <span>"moduleResolution": "node", // Resolve modules using Node.js style </span> <span>"isolatedModules": true, // Unconditionally emit imports for unresolved files </span> <span>"resolveJsonModule": true, // Include modules imported with .json extension </span> <span>"noEmit": true, // Do not emit output (meaning do not compile code, only perform type checking) </span> <span>"jsx": "react", // Support JSX in .tsx files </span> <span>"sourceMap": true, // Generate corrresponding .map file </span> <span>"declaration": true, // Generate corresponding .d.ts file </span> <span>"noUnusedLocals": true, // Report errors on unused locals </span> <span>"noUnusedParameters": true, // Report errors on unused parameters </span> <span>"incremental": true, // Enable incremental compilation by reading/writing information from prior compilations to a file on disk </span> <span>"noFallthroughCasesInSwitch": true // Report errors for fallthrough cases in switch statement </span> <span>}, </span> <span>"include": [ </span> <span>"src/**/*" // *** The files TypeScript should type check *** </span> <span>], </span> <span>"exclude": ["node_modules", "build"] // *** The files to not type check *** </span><span>} </span>來源:react-typescript-cheatsheet鉤鉤>
>這裡的美在於歧視工會的有用性。請注意,操作如何具有兩個外觀相似對象的結合。屬性類型是字符串文字。此字符串和類型字符串之間的區別在於,該值必須匹配該類型中定義的 >本節涵蓋了與React一起使用打字稿時人們絆倒的最常見用例。我們希望通過分享這一點,您將避免陷阱,甚至與他人分享這些知識。 處理表單事件 >最常見的情況之一是正確鍵入以形式的輸入字段上使用的Onchange。這是一個示例: 擴展組件props >有時您想將一個組件聲明的組件道具提取並將其擴展到另一個組件上。但是您可能需要修改一兩個。好吧,還記得我們如何看待鍵入組件道具,類型或接口的兩種方法?根據您使用的方式,確定瞭如何擴展組件道具。讓我們首先使用類型來查看方式: 如果您使用接口聲明了道具,那麼我們可以使用關鍵字擴展到本質上“擴展”該接口,但進行了一兩個修改:
>您可以在打字稿手冊中閱讀有關這兩個概念的更多信息:
例如,如果您使用的是開玩笑,則可以通過運行來做到這一點: 這將在您的項目中使用開玩笑時為您提供添加的類型安全。 簡短的答案是“取決於”。在大多數情況下,如果您要構建Web應用程序,它們可能會在DevDedipedies下進行。但是,如果您在打字稿中編寫了一個React庫,則可能需要將它們包括在依賴項中。 在堆棧溢出上有一些答案,您可以查看更多信息。
>
第一個選項意味著您根據軟件包名稱創建文件並將其放在根部。例如,如果我們需要用於包裝Banana-JS的類型,那麼我們可以在根上創建一個名為Banana-js.d.ts的基本聲明文件
>更徹底的聲明文件將是您添加圖書館/軟件包的類型: 如果您從未寫過聲明文件,那麼我們建議您查看官方打字稿手冊中的指南。
如果您想取得聯繫,請在本文上分享反饋或聊天有關兩種技術的聊天,您可以在Twitter @jsjoeio上與我聯繫。 進一步閱讀 如果您想深入研究,這裡有一些我們建議的資源: >官方打字稿手冊 打字稿遊樂場 >提高您的打字稿技能的實用方法 >首先設置帶有Typescript的新React Project。您可以使用諸如使用打字稿模板創建React App之類的工具,也可以在現有React項目中手動配置Typescript。 反應typeScript:React typeScript,另一方面,在React Application中使用TypeScript,typescript,靜態鍵入JavaScript發展。使用React TypeScript,開發人員使用Typescript的語法編寫其React組件。這種方法提供了一個重要的優勢:開發過程中的靜態檢查。打字稿使開發人員為Prop,State和其他數據定義類型和接口,這些類型和接口可以在編譯時而不是運行時捕獲與類型相關的錯誤。這會導致改進的代碼質量,增強的代碼可預測性以及降低運行時錯誤。總而言之,react.js是用於構建用戶界面的JavaScript庫,而React TypeScript是同一庫,但與Typescript集成以提供增強的typemcript輸入安全和開發支持。 React.js和React Typescript之間的選擇取決於項目需求,開發人員的偏好以及靜態鍵入對於特定應用程序的重要性。這兩個選項都是有效的,並且廣泛用於Web應用程序和用戶界面的開發。 >開始使用Typecript或JavaScript啟動React項目取決於各種考慮。 <span>yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react --dev
</span>
>
如您所見,鉤子不會為React和打字條項目的性質增添太多複雜性。如果有的話,他們將自己很好地適合二人組。
常見用例
npx create-react-app my-app <span>--template typescript
</span>
<span>{
</span> <span>"compilerOptions": {
</span> <span>"target": "es5", // Specify ECMAScript target version
</span> <span>"lib": [
</span> <span>"dom",
</span> <span>"dom.iterable",
</span> <span>"esnext"
</span> <span>], // List of library files to be included in the compilation
</span> <span>"allowJs": true, // Allow JavaScript files to be compiled
</span> <span>"skipLibCheck": true, // Skip type checking of all declaration files
</span> <span>"esModuleInterop": true, // Disables namespace imports (import * as fs from "fs") and enables CJS/AMD/UMD style imports (import fs from "fs")
</span> <span>"allowSyntheticDefaultImports": true, // Allow default imports from modules with no default export
</span> <span>"strict": true, // Enable all strict type checking options
</span> <span>"forceConsistentCasingInFileNames": true, // Disallow inconsistently-cased references to the same file.
</span> <span>"module": "esnext", // Specify module code generation
</span> <span>"moduleResolution": "node", // Resolve modules using Node.js style
</span> <span>"isolatedModules": true, // Unconditionally emit imports for unresolved files
</span> <span>"resolveJsonModule": true, // Include modules imported with .json extension
</span> <span>"noEmit": true, // Do not emit output (meaning do not compile code, only perform type checking)
</span> <span>"jsx": "react", // Support JSX in .tsx files
</span> <span>"sourceMap": true, // Generate corrresponding .map file
</span> <span>"declaration": true, // Generate corresponding .d.ts file
</span> <span>"noUnusedLocals": true, // Report errors on unused locals
</span> <span>"noUnusedParameters": true, // Report errors on unused parameters
</span> <span>"incremental": true, // Enable incremental compilation by reading/writing information from prior compilations to a file on disk
</span> <span>"noFallthroughCasesInSwitch": true // Report errors for fallthrough cases in switch statement
</span> <span>},
</span> <span>"include": [
</span> <span>"src/**/*" // *** The files TypeScript should type check ***
</span> <span>],
</span> <span>"exclude": ["node_modules", "build"] // *** The files to not type check ***
</span><span>}
</span>
<span>yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react --dev
</span>
兩種方法都解決了問題。由您決定要使用哪種。就個人而言,擴展界面感覺更可讀性,但最終取決於您和您的團隊。
是否適用於諸如Apollo之類的GraphQl客戶端,還是用於使用React測試庫等測試,我們經常發現自己使用React和Typecript項目中的第三方庫。發生這種情況時,您要做的第一件事就是查看是否有一個帶有打字稿類型定義的@Types軟件包。您可以通過運行:
來做到這一點
module<span>.exports = {
</span> <span>parser: '@typescript-eslint/parser', // Specifies the ESLint parser
</span> <span>extends: [
</span> <span>'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react
</span> <span>'plugin:@typescript-eslint/recommended', // Uses the recommended rules from @typescript-eslint/eslint-plugin
</span> <span>],
</span> <span>parserOptions: {
</span> <span>ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
</span> <span>sourceType: 'module', // Allows for the use of imports
</span> <span>ecmaFeatures: {
</span> <span>jsx: true, // Allows for the parsing of JSX
</span> <span>},
</span> <span>},
</span> <span>rules: {
</span> <span>// Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
</span> <span>// e.g. "@typescript-eslint/explicit-function-return-type": "off",
</span> <span>},
</span> <span>settings: {
</span> <span>react: {
</span> <span>version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use
</span> <span>},
</span> <span>},
</span><span>};
</span>
<span>yarn add prettier eslint-config-prettier eslint-plugin-prettier --dev
</span>
是否應該將這些保存為我的軟件包中的依賴項或dev依賴性。
npx create-react-app my-app <span>--template typescript
</span>
這不會為您提供鍵入安全性,但會取消阻止您。 <span>{
</span> <span>"compilerOptions": {
</span> <span>"target": "es5", // Specify ECMAScript target version
</span> <span>"lib": [
</span> <span>"dom",
</span> <span>"dom.iterable",
</span> <span>"esnext"
</span> <span>], // List of library files to be included in the compilation
</span> <span>"allowJs": true, // Allow JavaScript files to be compiled
</span> <span>"skipLibCheck": true, // Skip type checking of all declaration files
</span> <span>"esModuleInterop": true, // Disables namespace imports (import * as fs from "fs") and enables CJS/AMD/UMD style imports (import fs from "fs")
</span> <span>"allowSyntheticDefaultImports": true, // Allow default imports from modules with no default export
</span> <span>"strict": true, // Enable all strict type checking options
</span> <span>"forceConsistentCasingInFileNames": true, // Disallow inconsistently-cased references to the same file.
</span> <span>"module": "esnext", // Specify module code generation
</span> <span>"moduleResolution": "node", // Resolve modules using Node.js style
</span> <span>"isolatedModules": true, // Unconditionally emit imports for unresolved files
</span> <span>"resolveJsonModule": true, // Include modules imported with .json extension
</span> <span>"noEmit": true, // Do not emit output (meaning do not compile code, only perform type checking)
</span> <span>"jsx": "react", // Support JSX in .tsx files
</span> <span>"sourceMap": true, // Generate corrresponding .map file
</span> <span>"declaration": true, // Generate corresponding .d.ts file
</span> <span>"noUnusedLocals": true, // Report errors on unused locals
</span> <span>"noUnusedParameters": true, // Report errors on unused parameters
</span> <span>"incremental": true, // Enable incremental compilation by reading/writing information from prior compilations to a file on disk
</span> <span>"noFallthroughCasesInSwitch": true // Report errors for fallthrough cases in switch statement
</span> <span>},
</span> <span>"include": [
</span> <span>"src/**/*" // *** The files TypeScript should type check ***
</span> <span>],
</span> <span>"exclude": ["node_modules", "build"] // *** The files to not type check ***
</span><span>}
</span>
摘要如果您想看到此操作,可以在github上看到此示例。
這些建議中的許多建議直接來自React-Typecript-Cheatsheet。如果您正在尋找有關任何反應類型的特定示例或詳細信息,那麼這是一個可以去的地方。我們也歡迎捐款!
>另一個很棒的資源是打字稿手冊。這是由打字稿團隊保持最新的,並提供了該語言內部工作背後的示例和深入的解釋。
您是否知道可以在瀏覽器中使用打字稿代碼測試反應?您要做的就是導入反應。這是一個鏈接,可以讓您開始。
>
>閱讀我們的實用方法指南,以提高您的打字條技能,以便在您前進的過程中為自己的持續學習準備。
關於與打字稿反應的常見問題
>您可以將React與Typescript使用嗎?實際上,在網絡開發社區中,將反應與打字稿結合起來變得越來越流行。 Typescript是JavaScript的靜態鍵入超集,可提供增強的工具和鍵入安全性,使其成為構建可靠和可維護的反應應用程序的絕佳選擇。
>與TypeScript使用React時,您通常將React組件作為打字稿類或與功能性組件一起創建打字稿功能簽名。 Typescript允許您為道具和狀態定義強大的類型,從而降低運行時錯誤的風險並使代碼庫更可預測。此外,在現代代碼編輯器中,打字稿的自動完成和類型檢查在開發過程中提供了寶貴的幫助。 要使用Typescript啟動React Project,您可以在現有React Project中使用Typecript模板創建React App之類的工具。使用Typescript,您可以在用React構建動態和交互式用戶界面時享受靜態鍵入的好處,從而產生更可靠且可維護的Web應用程序。
>如何在React Apps中使用TypeScript?
接下來,使用Typescript編寫您的React組件。您可以使用打字稿功能簽名創建功能組件,也可以使用TypeScript類作為類組件。打字稿允許您指定道具類型和狀態類型,從而在代碼編輯器中提供強大的類型檢查和自動完成支持。如果您在React應用中使用第三方庫或軟件包,請確保為這些依賴項安裝打字稿類型定義。許多受歡迎的庫都有社區維護的打字稿類型聲明在肯定型上可用。用於開發的編程語言。
react.js(JavaScript):react.js通常稱為React,是一個用於構建用戶界面的JavaScript庫。使用React.js時,開發人員通常會在普通的JavaScript中編寫其應用程序,通常利用現代JavaScript功能(例如ES6和ES7)。 React.js的一個值得注意的特徵是,它默認情況下不會強制執行嚴格的鍵入。結果,開發人員依靠運行時檢查和工具(例如proptypes)進行類型驗證和錯誤檢測。 >我是否應該從typecript?
從Typescript開始:當您優先考慮強型安全性並改進的情況下,從Typescript開始就可以是有利的。開發工具。 Typescript的靜態類型檢查有助於在編譯時捕獲錯誤,從而導致更健壯和可維護的代碼。如果您正在從事一個龐大或複雜的項目,那麼Typescript可能特別有益於防止錯誤並使代碼庫更易於管理。 TypeScript還通過類型定義提供增強的代碼文檔,可以改善團隊內的代碼可讀性和協作。
選擇JavaScript:選擇JavaScript可能更適合較小的項目,或者當您在緊迫的期限下工作時。 JavaScript更輕巧,並且學習曲線較短,因此設置並開始更快。如果您的團隊缺乏打字稿的經驗或項目要求不需要強大的打字,那麼JavaScript可能是實用的選擇。此外,JavaScript生態系統還擁有大量的庫和資源集合,從而更容易找到您的項目的解決方案和支持。
以上是與打字稿反應:最佳實踐的詳細內容。更多資訊請關注PHP中文網其他相關文章!