Vite 从入门到精通 | 集成 TypeScript

3,210 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

Vite 从入门到精通 | 集成 TypeScript

Vite 天生支持 Ts 语法, 但是只编译, 不校验

手动进行校验不输出 tsc --noEmit

测试 Vite 可以直接编译 ts 文件么?

创建 test.ts

// vite-css-vue3/src/test.ts
interface A {
    name: string
}

export const a: A = {
    name: "jocker",
    age: 18   // 故意编写错误
}

在 App.jsx 中使用定义的状态 a

// App.jsx
import { defineComponent } from "@vue/runtime-core";
import "@style/index.css"
import "@style/index.less"
import classes from '@style/test.module.css'
import {a} from './test'

export default defineComponent({
    setup() {
        return () => {
            return <div class={`root  ${classes.moduleClass}`}>Hello  {a.name}</div>
        }
    }
})

image.png

结论

  • vite 可以直接编译 ts 文件

  • vite 将 ts 文件编译成 js 文件, 但是不做ts语法校验

如何才能做校验呢?

方案 1 package.json 文件 增加校验命令

  • 首先安装 typescript yarn add typescript

  • 增加 tsconfig.json 配置

    // tsconfig.json
    {
        "compilerOptions": {
            "target": "esnext",
            "module": "esnext",
            "moduleResolution": "node",
            "strict": true,
            "jsx": "preserve",
            "sourceMap": true,
            "resolveJsonModule": true,
            "esModuleInterop": true,
            "lib": ["esnext","dom"]
        },
        "include": [
            "src/**/*.ts",
            "src/**/*.d.ts",
            "src/**/*.tsx",
            "src/**/*.vue",
        ],
    }
    
  • 配置 tsc 命令

    "scripts": {
      "build": "tsc --noEmit && vite build"
    }
    
  • 执行 yran build 命令

    yarn build
    yarn run v1.22.4
    warning package.json: No license field
    $ tsc --noEmit && vite build
    src/test.ts:7:5 - error TS2322: Type '{ name: string; age: number; }' is not assignable to type 'A'.
      Object literal may only specify known properties, and 'age' does not exist in type 'A'.
    
    7     age: 18
          ~~~~~~~
    
    
    Found 1 error.
    
    error Command failed with exit code 2.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
    

    到此, ts 的错误就会被检测出来

对 vue 文件做 ts 校验, 需要做 vue-tsc for SFC

yarn add vue-tsc -D

配置 tsc 命令

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

isolatedModules | tsconfig.json 配置项

  • Exports of Non-Value Identifiers
  • Non-Module Files
  • References to const enum members

client types

  • Asset imports
  • Env 环境变量
  • HMR hot api