create-react-app添加對TypeScript支援
- 2020 年 11 月 18 日
- 筆記
- create-react-app, reactjs, typescript
背景
最近一直在重構react項目,由於項目歷史原因,將之前parcel打包工具換成了webpack,並選擇了使用create-react-app作為項目開發腳手架。
接著就是把項目中flow類型檢查工具移除掉了,替換成typescript。
相關文檔
讓項目支援ts的兩種方式
- 使用typescript創建react-app項目
yarn create react-app my-app --typescript
- 要將 TypeScript 添加到 Create React App 項目
yarn add typescript @types/node @types/react @types/react-dom @types/jest
在Create React App項目中添加支援ts
- 安裝typescript及聲明類型
yarn add typescript @types/react @types/react-dom @types/node @types/jest
- 配置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擴展名
- 創建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 排除的編譯的目錄
更多配置可以查看//www.typescriptlang.org/docs/handbook/tsconfig-json.html
{
"compilerOptions": {
/* Visit //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. */
}
}
參考閱讀
- //zhuanlan.zhihu.com/p/100744558
- //blog.csdn.net/qq_36154659/article/details/107645982
- //stackoverflow.com/questions/64115884/error-when-updating-create-react-app-to-4-0-with-typescript-template