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

Note: Vite also relies on Node.js, so the Node environment needs to be installed, and Vite requires Node to be at least version 12.

We are not going to build a complete project from Vite scaffolding (NPM init vite@latest) as described in the official Vite documentation, because it is hard to understand what Vite does for us in this project. So what we’re going to do here is start from scratch, install the Vite tool, and then use Vite to process our code step by step.

First, let’s install the Vite tool. Here we only want to package the current project using Vite under the current project (the basic use of Vite), so we choose partial installation:

npm install vite -D
Copy the code

Of course, you can also install globally:

npm install vite -g
Copy the code

After installing Vite, we want to use Vite to do something with the code in our project. How do we do that? The index. HTML file was opened on the local Server using the Live Server plugin. Now we can turn off the local Server using the Live Server plugin:

After shutting down the Live Server, we will execute the NPX vite command (local vite will be used to build the local Server) to start the project:

NPX vite node_modules/. Bin /vite

NPX vite will set up a local service on port 3000 of localhost by default (this service is not related to the previous Live Server), we can open http://localhost:3000/ :

As you can see, Vite already supports the code in our project. In this process, Vite will build the code in our SRC, and then build a local service, which will be accessed by the browser. The Vite service will provide the corresponding source code.

Also, you’ll find that Vite is very fast to build because it’s based on ES Modules and converts code directly into ES Modules code, and our code is already ES Modules code, so it’s very fast to convert.

So, what’s the difference between running on a Live Server without a build tool and running on a Vite native service now? There are three differences:

  1. The file suffix can now be omitted (this is also available in Webpack), such as SRC /main.js files that were previously imported can now omit the.js suffix:

    import _ from '.. /node_modules/lodash-es/lodash.default'
    import { sum } from './js/math'
    Copy the code
  2. SRC /main.js import lodash-es module can now be written like this:

    import _ from 'lodash-es'
    Copy the code
  3. The lodash-es module imported from SRC /main.js can be packaged into a single file, which eliminates the performance cost caused by hundreds of dependent files sending hundreds of requests:

    Of course, there are a few additional files (client, env.js) that are automatically loaded internally by Vite because there are other things that need to be done inside, so it will load some environment-specific stuff.

So Vite did do something for us. Above, is the most basic use of Vite process.