Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Vite from entry to master | integrated TypeScript

Vite naturally supports Ts syntax, but only compiles, not validates

Manual validation does not output TSC –noEmit

Can test Vite compile TS files directly?

Create test. Ts

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

export const a: A = {
    name: "jocker".age: 18   // Intentional error writing
}
Copy the code

Use the defined state A in app.jsx

// 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={`rootThe ${classes.moduleClass} `} >Hello  {a.name}</div>}}})Copy the code

conclusion

  • Vite can compile TS files directly

  • Vite compiles ts files to JS files, but does not do TS syntax verification

How can I do a check?

Solution 1 Add verification command to package.json file

  • Install typescript YARN Add typescript first

  • Added tsconfig.json configuration

    // 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",]}Copy the code
  • Configure the TSC command

    "scripts": {
      "build": "tsc --noEmit && vite build"
    }
    Copy the code
  • Run the yran build command

    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.
    Copy the code

    At this point, the TS error will be detected

Vue – TSC for SFC is required to perform TS verification on VUE files

yarn add vue-tsc -D
Copy the code

Configure the TSC command

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

IsolatedModules | tsconfig. Json configuration items

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

client types

  • Asset imports
  • Env environment variable
  • HMR hot api