“This is the 16th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

1. ViteTypeScriptThe support of

Does Vite support TypeScript processing by default? We can test that out. In the SRC folder, create a ts folder. In the ts folder, create a mul.ts file.

export default function(num1: number, num2: number) :number {
  return num1 * num2;
}
Copy the code

Then we import the ts file in SRC /main.js and use the multiplication function inside:

After saving the file, let’s look at the effect in the browser:

As you can see, the console successfully printed a 10 by 20 result, which shows that Vite supports TS code by default.

Vite supports TypeScript natively-it uses ESbuild directly to compile TypeScript into JavaScript, simply importing ts files.

2. ViteThe default supportTypeScriptThe internal principles of

How does Vite support TS and preprocessor languages like Less?

Let’s look at the request message in the browser after the project starts:

You will notice that when the browser requests a local server built by Vite, it still requests the ts file mul. Ts and the title.less file.

In fact, Vite sets up a local server (unlike the Express local server used by Webpack-dev-server in Webpack, the KOA local server is used in Vite 1, In Vite 2 Connect library building is used in the local server (official document has instructions: cn. Vitejs. Dev/guide/migra… The Connect library is good for a basic server.

In our case, the browser is not requesting the mul.js file from the server, but the mul.ts file. Similarly, the browser is requesting the title.less file, but the less file and ts file cannot be directly handed to the browser for parsing. Because browsers can’t parse the code for either file type. So what does Vite do internally? The code in these two files (mul.ts and title.less) will be converted to ES6 JS code (less/ CSS will also be converted to JS code). The style code is then put into the

If we look at the requests in the browser, we’ll see that the requests are still.ts,.less files. This is because Connect, the server in Vite, forwards our request, takes the TS and less compiled code, and returns it to the browser, which can parse it directly.

In the Network panel of your browser, click on the Mul. ts file and click on the Response TAB. You will find the js code inside, and it is the ES6 JS code:

Similarly, title.less is full of JS code:

All the js code in title.less does is insert styles from the less file into the HTML as a

That’s how the Vite server works.