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中文网其他相关文章!