How to better use TS in Vite

TS is a type checking tool for JS , which checks some invisible problems that may exist in our code; at the same time, it can enable our compiler to have some syntax prompting functions.

If we use create-vue (vue3 official scaffolding tool) to create a project, the project is based on Vite and TypeScript is ready for TS development directly.

In this article, we discuss the support for TS in any installation project (without scaffolding).

Vite is naturally supportive of TS

We create and initialize a project (yarn init -y), install vite (yarn add Vite -D).

Then, create an entry file index.html and introduce our custom main.ts file

<script src="./main.ts" type="module"></script> 

main.ts file

let tip:string = "这是一个vite项目,使用了ts语法"
console.log('tip: ', tip); 

We use the vite command to start the project in the terminal, and we can see that the console outputs what we printed.

In this demo, we only installed vite for ordinary projects, without installing any ts-related plug-ins.

It can be seen from this that vite has already processed the support for ts internally, and we can use it directly.

Use plugins to enhance our capabilities

In a pure vite project, vite will not prompt ts syntax errors and block its compilation by default.

NOTE: We are talking about the case without using any scaffolding!

For example, we assign the character type tip to a number in main.ts

let tip:string = "这是一个vite项目,使用了ts语法"
tip = 2
console.log('tip: ', tip); 

Such TS syntax is problematic, but it will still compile successfully.

In order to strictly demand ourselves and improve the code level, we should let the error output in the console prevent compilation and force us to solve the problem.

This function can be realized by vite-plugin-checker .

vite-plugin-checker is a plug-in that can run TypeScript, VLS, vue-tsc, and ESLint in a worker thread. It can block compilation and display error messages on the console and browser according to the configuration.

Dependency installation

npm i vite-plugin-checker -D 

Create a vite.config.js configuration file in the root directory and introduce vite-plugin-checker

// vite.config.js
import checker from "vite-plugin-checker";
import { defineConfig } from "vite";
export default defineConfig({plugins: [checker({typescript: true,}),],
}); 

At this time, running the project directly will still report an error, because the ts configuration file tsconfig.json is also required. We use the command line to generate

npx tsc --init 

After creating the tsconfig.json configuration file, restart the vite service, and you will find that the syntax error of TS has been output

console output

browser output

Now, as long as we write a problematic TS, vite will report an error, let us find the problem and deal with it in time! It smells so good (death)!

TS check before packaging

Vite only performs translation of .ts files and does not perform any type checking. This means that even if there is a grammatical error of Ts in our project, the packaging can proceed normally.

As an excellent developer, how can we allow such a situation to exist?

We can use the following syntax to perform code inspection at packaging time:

  • Run tsc --noEmit in the build script
  • For .vue files, you can install vue-tsc and run vue-tsc --noEmit to type check your *.vue files

We configure it in package.json for verification:

// package.json"scripts": {"dev": "vite",// 如果ts检查不通过,vite build就不会执行"build": "tsc --noEmit && vite build",}, 

Then execute npm run build to execute the packaging command

Sure enough, the compilation was blocked at this time.

The execution principle of tsc --noEmit

This is the built-in syntax of ts, and it has nothing to do with vite. When executing tsc --noEmit , TSC will read the configuration file to obtain parameter values. The function of --noEmit is to only check and not compile and output. If our code is error-free, it will exit directly, otherwise it will report an error.

IntelliSense for TypeScript

For the knowledge of environment variables, you can refer to juejin.cn/post/717201…

By default, Vite provides type definitions for import.meta.env in vite/client.d.ts . But some custom .env[mode] files don't have TypeScript intellisense.

To do this, we can create an env.d.ts file in the src directory, and then add definitions as follows:

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

interface ImportMetaEnv {// 自定义内容...readonly VITE_APP_TITLE: stringreadonly VITE_APP_HAHA: stringreadonly VITE_APP_WOCAO: string// 自定义内容...
}

interface ImportMeta {readonly env: ImportMetaEnv
} 

Note: The template must be installed to write, this method is for all projects, and the same is true for scaffolding projects

Example:

Test in main.ts

As shown in the picture, we can see that our smart prompt has taken effect.

Here I encountered an error report in vscode, which is just an error report of ts, and has nothing to do with the setting of our variables.

The error problem is also very simple. ts now thinks that our project is based on commonjs, so there is no import.meta attribute.

We can change the value of module to "es2022".

At last

I recently found a VUE document, which summarizes the various knowledge points of VUE and organizes it into "36 skills that Vue development must know". The content is relatively detailed, and the explanation of each knowledge point is also in place.



Friends in need, you can click the card below to receive and share for free

Guess you like

Origin blog.csdn.net/web22050702/article/details/128703487