# TypeScript环境配置

## node环境

开源社区中有一个名为[ts-node](https://link.juejin.cn/?target=https%3A%2F%2Ftypestrong.org%2Fts-node%2F)的库,它可以运行时解析`ts`,执行node的`API`,如下所示:

```bash
npm install -D typescript | yarn add typescript -D
npm install -D ts-node | yarn add ts-node -D
npm install -D tslib @types/node | yarn add tslib @types/node -D
```

在项目根目录创建`tsconfig.json`文件,文件可以理解为存放编译`TS`的配置文件,具体的配置请移步[tsconfig配置](https://link.juejin.cn/?target=https%3A%2F%2Fwww.tslang.cn%2Fdocs%2Fhandbook%2Ftsconfig-json.html),我的配置文件如下所示:

```json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"outDir": "./output",
"types": [
"webpack-env"
],
"declaration": true,// 是否生成声明文件
"declarationDir": "dist/type",// 声明文件打包的位置
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"exclude": [
"node_modules"
]
}
```

## React

方式一:

```bash
npx create-react-app my-app --template typescript
```

方式二:

1.安装相关库

```javascript
npm i react react-dom react-redux typescript --save
复制代码
```

2.安装@types声明库

```javascript
npm i @types/react @types/react-dom @types/react-redux --save-dev
```

### tsconfig.json

```json
{
"compilerOptions": {
"target": "es5", // 编译的目标
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": false,
"jsx": "preserve",
"baseUrl": "./",
"paths": {
"@": ["src/"]
}
},
"include": ["./src/**/*"]
}
```

最后修改:2021 年 11 月 19 日
如果觉得我的文章对你有用,请随意赞赏