Typescript - 配置

156 阅读4分钟

1、安装 TypeScript 及相关依赖

在 webpack 项目中安装 TypeScript 和类型定义文件

npm install typescript ts-loader @types/node @types/webpack --save-dev

在 webpack 中配置 loader

{
    ...
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    ...
}

2、适配 React

安装相关依赖

npm install react react-dom
npm install @types/react @types/react-dom --save-dev

3、适配 eslint

//  typescript 相关插件
npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

// react 相关插件
npm install eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y --save-dev

创建或更新 eslint.config.js 文件:

。。。

3、适配 babel

安装 @babel/preset-typescript

npm install @babel/preset-typescript --save-dev

在 Babel 配置文件中添加 TypeScript 支持:

{
    "presets": [
        "@babel/preset-env", 
        "@babel/preset-react", 
        "@babel/preset-typescript"
    ]
}

和 ts-loader 的区别和关系

  • 1、编译器 vs. 转换器:
    • ts-loader 使用 TypeScript 编译器 tsc 进行编译,不仅转换语法,还进行类型检查。
    • @babel/preset-typescript 使用 Babel 进行转换,仅转换语法,不进行类型检查。
  • 2、应用场景:
    • ts-loader 通常用于 Webpack 构建流程中,处理项目中的 TypeScript 文件。
    • @babel/preset-typescript 通常用于需要将 TypeScript 代码转换为纯 JavaScript 代码的场景,特别是在使用 Babel 进行其他转换(如 ES6 to ES5)时。
  • 3、配置复杂性:
    • ts-loader 依赖于 tsconfig.json 文件,配置相对简单。
    • @babel/preset-typescript 需要与 Babel 的其他配置(如 .babelrc 或 babel.config.js)一起使用,配置可能更复杂。

4、编辑生成的 tsconfig.json 文件

// tsconfig.json
{
  // 包含所有编译选项
  "compilerOptions": {

    /* Language and Environment */
    "target": "esnext", // 编译成js的版本(es5, es6, es2015,... , es2022, esnext)
    "lib": [ // 指定编译过程中需要包含的库文件
      "dom", // 如:DOM相关操作使用dom
      "dom.iterable",
      "esnext"
    ],
    // "jsx": "preserve", // 制定 jsx 的开发环境(preserve、react-native、react)
    // "experimentalDecorators": true,  // 是否启用试验特性
    // "emitDecoratorMetadata": true,
    // "jsxFactory": "",
    // "jsxFragmentFactory": "",
    // "jsxImportSource": "",
    // "reactNamespace": "",
    // "noLib": true,
    // "useDefineForClassFields": true,
    // "moduleDetection": "auto",


    /* Modules */
    "module": "esnext", // 编译后模块系统(ommonjs, amd, umd, system, es2015, es2020, es2022, esnext)
    "rootDir": "./src", // 指定源代码的根目录,输出文件的目录结构会相对于 rootDir 进行生成
    "moduleResolution": "node", // 指定模块解析策略 (node, node16, nodenext, classic)
    "baseUrl": "./", // 1、设置模块解析的基础目录 2、结合 paths 配置使用
    paths: { // 1、设置模块解析的路径映射 2、结合 baseUrl 使用
      "@/*": ["src/*"] // "./src/*"
    },
    // "rootDirs": [],  // 构建好的文件存放跟路径
    "typeRoots": [ // 指定类型定义文件(.d.ts 文件)的搜索路径
      "./node_modules/@types", // 默认值
      "./src" // 自定义
    ],
    // "types": [ // 指定项目中使用的全局类型定义文件(优先于 typeRoots)
    //   "node",
    //   "express",
    //   "custom-type"
    // ],
    "allowUmdGlobalAccess": true  // 允许在模块中访问 UMD 全局变量
    // "moduleSuffixes": [],
    "resolveJsonModule": true, // 允许导入 JSON 模块
    // "noResolve": true, // 允许导入 JSON 模块

    /* JavaScript Support */
    "allowJs": true, // 允许编译 JavaScript 文件
    "checkJs": true, // 对 JavaScript 文件进行类型检查
    // "maxNodeModuleJsDepth": 1,


    /* Emit */
    // "declaration": true, // 编译的时候是否生成 .d.ts 文件
    // "declarationDir": "./",  // 生成声明文件的输出路径。
    // "declarationMap": true,
    // "emitDeclarationOnly": true,
    // "sourceMap": true,
    //  "outFile": "./dist/app.js" // 所有文件编译后合成一个app.js文件,仅支持 "amd" 和 "system" 模块
    "outDir": "./dist", // 指定编译输出目录
    // "removeComments": true, // 是否去掉注释
    "noEmit": false,  // 不生成编译后的文件
    // "importHelpers": true,
    // "importsNotUsedAsValues": "remove",
    // "downlevelIteration": true,
    // "sourceRoot": "",
    // "mapRoot": "",
    // "inlineSourceMap": true,
    // "inlineSources": true,
    // "emitBOM": true,
    // "newLine": "crlf",
    // "stripInternal": true,
    "noEmitHelpers": true, // 不生成输出文件,仅进行类型检查
    // "noEmitOnError": true, // 有报错时,不生成编译后的文件
    // "preserveConstEnums": true,
    // "preserveValueImports": true,


    /* Interop Constraints */
    // "isolatedModules": true, // 将每个文件作为单独的模块
    "allowSyntheticDefaultImports": true, // 允许从没有默认导出的模块中使用默认导入
    "esModuleInterop": true, // 启用对 CommonJS 和 ES 模块的互操作性支持
    // "preserveSymlinks": true,
    "forceConsistentCasingInFileNames": true, // 强制文件名大小写一致,避免因文件系统不区分大小写导致的问题


    /* Type Checking */
    "strict": true, // 启用所有严格类型检查选项
    "noImplicitAny": true, // 禁止隐式 any 类型
    // "strictNullChecks": true, // 是否可以赋值为null、undefined
    // "strictFunctionTypes": true,
    // "strictBindCallApply": true,
    // "strictPropertyInitialization": true,
    "noImplicitThis": true, // 禁止 this 的隐式类型为 any
    // "useUnknownInCatchVariables": true,
    // "alwaysStrict": true, // 编译后的文件,是否开启严格模式( import、export本身就是严格模式)
    "noUnusedLocals": true, // 禁止未使用的局部变量
    "noUnusedParameters": true, // 禁止未使用的参数
    // "exactOptionalPropertyTypes": true,
    "noImplicitReturns": true, //禁止函数中有未返回值的情况
    // "noFallthroughCasesInSwitch": true, // 报告 switch 语句中缺少 break 的情况。
    // "noUncheckedIndexedAccess": true,
    // "noImplicitOverride": true,
    // "noPropertyAccessFromIndexSignature": true,
    // "allowUnusedLabels": true,
    // "allowUnreachableCode": true,  // 不报告,执行不到的代码错误
    // 允许引入文件时携带后缀 如: './math.ts',只能在设置了 noEmit 或 emitDeclarationOnly 选项的情况下使用
    // 1、设置 noEmit 选项:如果你不需要生成编译后的 JavaScript 文件
    // 2、设置 emitDeclarationOnly 选项:如果你只需要生成类型声明文件(.d.ts)
    "allowImportingTsExtensions": true 

    /* Completeness */
    // "skipDefaultLibCheck": true,
    "skipLibCheck": true // 跳过对第三方库的类型检查,加快编译速度
  },
  "files": [ // 指定具体的文件列表需要被编译,不管"exclude"如何设置

  ],
  "include": [ // 指定哪些文件需要被编译(默认为根目录)
    "src/*.ts",
    "src/**/*.ts",
    "src/**/*.d.ts"
  ],
  "exclude": [ // 指定哪些文件不需要被编译
    "node_modules",
    "**/*.spec.ts"
  ],
  // "extends": "" // 继承其他 tsconfig.json 文件的配置
}