添加typescript到已有React项目

安装依赖

官方文档

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

# or

yarn add typescript @types/node @types/react @types/react-dom @types/jest

添加配置文件

在项目根目录创建配置文件 tsconfig.json

如果你使用了不支持 TS 的库,需要设置 skipLibCheck 为 true。

一般,我们还需要设置允许 any 类型,将 noImplicitAny 设置为 false。

{
    "compilerOptions": {
        "skipLibCheck": true,
        "noImplicitAny": false,
        ......
    }
}

一份完整的配置文件 tsconfig.json

{
  "compilerOptions": {
    "skipLibCheck": true,
    "noImplicitAny": false,
    "outDir": "build/dist",
    "module": "esnext",
    "target": "esnext",
    "lib": ["esnext", "dom"],
    "sourceMap": true,
    "baseUrl": ".",
    "jsx": "react",
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "allowJs": true,
    "experimentalDecorators": true,
    "strict": true,
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "exclude": ["node_modules", "build", "scripts", "acceptance-tests", "webpack", "jest", "src/setupTests.ts", "tslint:latest", "tslint-config-prettier"]
}
© 2022  Arvin Xiang
Built with ❤️ by myself