TypeScript环境配置

node环境

开源社区中有一个名为ts-node的库,它可以运行时解析ts,执行node的API,如下所示:

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配置,我的配置文件如下所示:

{
  "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

方式一:

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

方式二:

1.安装相关库

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

2.安装@types声明库

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

tsconfig.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 日 06 : 24 PM