feng xiaohan

vite 中使用 ts

vite 中默认支持 ts,不需要额外配置。

vite-plugin-checker

它是一个可以在工作线程中运行 TypeScript、 VLS、 vue-tsc、 ESLint 的插件,可以根据配置,阻断编译,在控制台及浏览器展示报错信息。

基本使用

  • 安装:
npm i vite-plugin-checker -D
  • vite config 中配置:
// vite.config.js
import checker from "vite-plugin-checker";
import { defineConfig } from "vite";
export default defineConfig({
  plugins: [
    checker({
      typescript: true,
    }),
  ],
});
  • 生成 tsconfig.json 配置文件:
npm tsc --init
  • 指定需要进行 ts check 的文件:
// tsconfig.json
{
  "include": ["src/*.ts"]
}

注意:以上配置不影响正常打包,只是在运行的时候出报错。

打包前进行 ts 检查

vite 本身仅执行 .ts 文件的转译工作,并不执行任何类型检查。所以我们可以借助 ts 本身的类型检查功能,在打包前对代码进行类型检查:

"scripts": {
  "build": "tsc --noEmit && vite build"
}

对于 .vue 文件,可以安装 vue-tsc 然后运行 vue-tsc –noEmit 来对 *.vue 文件做类型检查。

原理:
tsc是 TypeScript 的编译器,它负责将 TypeScript 代码转换为 JavaScript 代码。tsc 会读取配置文件获取参数值,--noEmit 的作用是只进行检查,不进行编译输出。如果我们的代码无错,会直接退出,执行下一条语句,否则报错。

ts 智能提示

默认情况下,vite 在 vite/client.d.ts 中为import.meta.env提供了类型定义。但是如果我们设置了一些自定义的环境变量(.env[mode])是没有提示的,如果也想在浏览器环境代码中有智能提示,可以在env.d.ts中定义:

/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_APP_TITLE: string;
}
interface ImportMeta {
  readonly env: ImportMetaEnv;
}

注意:定义的文件名和文件位置其实不重要,重要的是需要在 tsconfig.json 配置将其文件进行 ts 检查:

{
  "include": ["src/*.ts", "env.d.ts"]
}