背景

最近一直在重构react项目,由于项目历史原因,将之前parcel打包工具换成了webpack,并选择了使用create-react-app作为项目开发脚手架。

接着就是把项目中flow类型检查工具移除掉了,替换成typescript。

相关文档

让项目支持ts的两种方式

  1. 使用typescript创建react-app项目
yarn create react-app my-app --typescript
  1. 要将 TypeScript 添加到 Create React App 项目
yarn add typescript @types/node @types/react @types/react-dom @types/jest

在Create React App项目中添加支持ts

  1. 安装typescript及声明类型
yarn add typescript @types/react @types/react-dom @types/node @types/jest
  1. 配置tsconfig.json
{
"compilerOptions": {
"target": "es5",// 目标语言的版本
"lib": ["dom", "dom.iterable", "es2015.promise", "esnext"],
// 编译时引入的 ES 功能库,包括:es5 、es6、es7、dom 等。// 如果未设置,则默认为: target 为 es5 时: ["dom", "es5", "scripthost"]
//target 为 es6 时: ["dom", "es6", "dom.iterable", "scripthost"]
"allowJs": true, // 允许编译器编译JS,JSX文件
"checkJs": true, // 允许在JS文件中报错,通常与allowJS一起使用
"skipLibCheck": true,
"esModuleInterop": true,// 允许export=导出,由import from 导入
"allowSyntheticDefaultImports": true,
"strict": true,// 开启所有严格的类型检查
"forceConsistentCasingInFileNames": true,
"module": "esnext",// 生成代码的模板标准
"moduleResolution": "node",// 模块解析策略,ts默认用node的解析策略,即相对的方式导入
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,// 不输出文件,即编译后不会生成任何js文件
"jsx": "react",//在 .tsx 中支持 JSX :React 或 Preserve
"strictFunctionTypes": false,// 不允许函数参数双向协变
"downlevelIteration": true,// 降级遍历器实现,如果目标源是es3/5,那么遍历器会有降级的实现
"noFallthroughCasesInSwitch": true,// 防止switch语句贯穿(即如果没有break语句后面不会执行)
"baseUrl": "./src" // 解析非相对模块的基地址,默认是当前目录
},
"include": ["src", "**/*.ts", "**/*.tsx"],
"exclude": ["./node_modules"]
}

这里需要注意的是,现有项目由于都是js文件,所有我们需要开启allowJs为true支持编译js文件,让之前的项目可以正常跑起来,

然后再慢慢的将之前的js代码改造成ts代码。

这里再说一下关于jsx、tsx和ts的区别

  • JSX,是一个 JavaScript 的语法扩展,在React框架中开始流行-
  • tsx,如要在typescript中使用jsx语法,则扩展名命名文件使用.tsx后缀
  • ts,typescript默认使用.ts扩展名
  1. 创建Content.tsx文件和content.ts文件
//Content.tsx

import React from 'react'
import { user } from './content' const Content: React.FC = () => {
const { name } = user
return (
<div>
hi,{name}
</div>
)
} export default Content //content.ts interface User {
name: string
} export const user: User = {
name: 'Kerry'
}

其他

上面的tsconfig.json文件我们也可以通过命令的方式进行创建

tsc --init

这里如果报错command not found: tsc,需要使用全局方式安装typescript yarn global add typescript

执行以上命令后,会为我们再根目录下生成一个默认的tsconfig.json文件

  • compilerOptions 用来配置编译选项
  • include 指定编译目录
  • exclude 排除的编译的目录

更多配置可以查看https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ /* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

参考阅读

create-react-app添加对TypeScript支持的更多相关文章

  1. 深入 Create React App 核心概念

    本文差点难产而死.因为总结的过程中,多次怀疑本文是对官方文档的直接翻译和简单诺列:同时官方文档很全面,全范围的介绍无疑加深了写作的心智负担.但在最终的梳理中,发现走出了一条与众不同的路,于是坚持分享出 ...

  2. 在 .NET Core 5 中集成 Create React app

    翻译自 Camilo Reyes 2021年2月22日的文章 <Integrate Create React app with .NET Core 5> [1] Camilo Reyes ...

  3. tap news:week5 0.0 create react app

    参考https://blog.csdn.net/qtfying/article/details/78665664 先创建文件夹 安装create react app 这个脚手架(facebook官方提 ...

  4. 使用create react app教程

    This project was bootstrapped with Create React App. Below you will find some information on how to ...

  5. 如何扩展 Create React App 的 Webpack 配置

    如何扩展 Create React App 的 Webpack 配置  原文地址https://zhaozhiming.github.io/blog/2018/01/08/create-react-a ...

  6. Create React App

    Facebook开源了React前端框架(MIT Licence),也同时提供了React脚手架 - create-react-app. create-react-app遵循约定优于配置(Coc)的原 ...

  7. Create React App 安装less 报错

    执行npm run eject 暴露模块 安装 npm i  less less-loader -D 1.打开 react app 的 webpack.config.js const sassRege ...

  8. [React] Use the Fragment Short Syntax in Create React App 2.0

    create-react-app version 2.0 added a lot of new features. One of the new features is upgrading to Ba ...

  9. [React] {svg, css module, sass} support in Create React App 2.0

    create-react-app version 2.0 added a lot of new features. One of the new features is added the svgr  ...

随机推荐

  1. 微信聊天记录导出为csv,并生成词云图

    微信聊天记录生成特定图片图云 首先贴上github地址 https://github.com/ghdefe/WechatRecordToWordCloud 来个效果图 提取聊天记录到csv参考教程 h ...

  2. 【C语言学习笔记】空间换时间,查表法的经典例子!知识就是这么学到的~

    我们怎么衡量一个函数/代码块/算法的优劣呢?这需要从多个角度看待.本篇笔记我们先不考虑代码可读性.规范性.可移植性那些角度. 在我们嵌入式中,我们需要根据实际资源的情况来设计我们的代码.比如当我们能用 ...

  3. UVA 10635 Prince and Princess—— 求LCS(最长公共子序列)转换成 求LIS(最长递增子序列)

    题目大意:有n*n个方格,王子有一条走法,依次经过m个格子,公主有一种走法,依次经过n个格子(不会重复走),问他们删去一些步数后,重叠步数的最大值. 显然是一个LCS,我一看到就高高兴兴的打了个板子上 ...

  4. document.all.WebBrowser为空或不是对象

    项目中也想用这个功能,发现出错,经过测试,一定要加<object id="WebBrowser" width=0 height=0 classid="CLSID:8 ...

  5. python web自动化上传文件工具

    工具下载地址:链接:https://pan.baidu.com/s/1cHdNHW 密码:56bp说明:1.WinSpy-1.0.2.7z解压即可.2.pywin32的exe程序,根据自己安装的pyt ...

  6. 小C和小派的缠绵爱情——C语言调用Python代码

    我妒忌你的开源,你眼红我的速度,不如我们就在一起吧! --------SJ2050 2019.4.9号更新:实现在未安装python环境的机子上运行调用了python程序的C语言代码! 文章目录 环境 ...

  7. laytable 前台删除后加载当前页数据。

    laytable一次性获取数据后,点击删除调用后台删除.返回成功状态后刷新当前页数据. 渲染方法: //渲染表格 function renderingTable(pageIndex, sourceDa ...

  8. docker 启动mysql 挂载宿主机目录

    在使用docker run 运行镜像获取容器时,有些容器会自动产生一些数据,为了这些数据会因为container (容器)的消失而消失,保证数据的安全,比如mysql 容器在运行中产生的一些表的数据, ...

  9. java8中哪个类用到了开放地址解决冲突

    hreadlocalmap使用开放定址法解决haah冲突,hashmap使用链地址法解决hash冲突

  10. 用c++获取随机数

    计算机的随机数都是由伪随机数,即是由小M多项式序列生成的,其中产生每个小序列都有一个初始值,即随机种子.(注意: 小M多项式序列的周期是65535,即每次利用一个随机种子生成的随机数的周期是65535 ...