A basis,

  1. Build a Vite project
npm init vite@latest
Copy the code
  1. The configuration file

The configuration file in the project directory is the vite. Config. js file. When you run vite on the CLI, Vite automatically parses this file.

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// Use the defineConfig utility function to get type hints without jsdoc annotations
export default defineConfig({
  plugins: [vue()]
})
Copy the code
  1. Scene configuration

If the configuration needs to be based on the (dev/serve or build) command or a different mode, you can choose to export the following functions:

import {defineConfig} from 'vite';
import vue from '@vitejs/plugin-vue';

// Use the defineConfig utility function to get type hints without jsdoc annotations
export default defineConfig(({command, mode}) = > {
  console.log(command, mode); // The command value is serve in the development environment and build in the production environment
  if (command === 'serve') {
    return {
      plugins: [vue()]
    };
  } else {
    return {
      plugins: [vue()] }; }});Copy the code

Two, vite why fast

Read the official document of Vite, its official document has given a very clear explanation vitejs.cn/guide/why.h…

  1. Improve the vite server startup speed

A packager-like build tool like WebPack packs all unbundled resources before starting the service, whereas Vite postsets this process and makes some optimizations to speed up server startup, as shown below:

(1) Pre-build dependencies through esbuild

Dependencies are pure JavaScript that doesn’t change at development time, mainly files in node_modules. This content usually contains multiple modular formats (CommonJS, UMD, ESM, etc.), so it needs to be converted to native ES modules. To complete this conversion process, Prebuild dependencies are introduced with esbuilds, which are faster to build than packers written in JavaScript because they are written in GO.

(2) Modern browsers support ESM format code

Because browsers support ESM code, the browser can take over some of the packaging, and Vite only needs to transform the source code when the browser requests it and provide it on demand.

  1. Speed up the update

In order to speed up the update, Vite has made many optimizations, mainly reflected in the following points:

(1) Reduce network requests

When esBuild prebuilds dependencies, it converts the ESM dependencies of many internal modules into a single module, thus reducing the number of network requests and improving page loading performance

(2) Cache

Requests from source modules are negotiated cached according to 304 Not Modified, while dependent module requests are strongly cached via cache-control: max-age=31536000,immutable, so they do Not need to be requested again once cached

3. Configuration items

For the convenience of users, Vite provides a lot of configuration items, mainly including 7 categories: sharing configuration, service development options, build options, preview options, dependency optimization options, SSR options, Worker options. I personally think the first three options are the most important, let’s take a look at the first three options.

3.1 Sharing Options

Shared options are configuration items that vite performs in both development and production environments. They are used to represent some general things, and I’ll show you a few that I think are important.

  1. root

For example, if the index.html file and SRC folder are under the testRoot file, the configuration is as follows:

export default defineConfig({
    root: './testRoot'.plugins: [vue()]
});
Copy the code
  1. base

Is used to set the file path, for example, according to the following Settings in the development environment after can be accessed through http://localhost:3000/testBase to the required page:

export default defineConfig({
    base: '/testBase/'.plugins: [vue()]
});
Copy the code
  1. mode

Used to indicate development or production mode, overrides both serve and build modes, and can also be overridden with the –mode option:

export default defineConfig({
    plugins: [vue()],
    mode: 'production'
});
Copy the code
  1. plugins

Plugins are used to solve the problem that pure vite provides out of the box. For example, @vitejs/plugin-vue provides support for Vue3 single file components:

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
    plugins: [vue()]
});
Copy the code
  1. publicDir

This configuration sets the static resource service files. The default configuration is the public file file. The files in this directory are provided at/during development and copied to the root directory of outDir during build.

export default defineConfig({
    plugins: [vue()],
    publicDir: './testPublicDir'
});
Copy the code
  1. resolve.alias

Use this configuration to set the alias of a file system path. If the path is set to an absolute path, the alias value of a relative path will be used unchanged:

export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            The '@': path.resolve(__dirname, './src')}}});Copy the code
  1. EnvDir and envPrefix

Sometimes you need to set some environment variables to be used in code. EnvDir allows you to set the directory of the environment variable file (default is the root directory), envPrefix allows you to set the prefix to be exposed to the environment variable (default is VITE_), Once set, this variable can be read in your code via import.meta.env. The files that can be read in this directory are as follows:

Env.[mode] # local # Load only in the specified mode, but git ignores itCopy the code

The content in the file can be set as follows:

VITE_TEST=test // Can be read
TEST=test // Cannot be read
Copy the code

3.2 Developing service options

In addition to the sharing options, you should also pay attention to the development services option when developing the environment. This option directly represents how we configure the Vite server. I think the common options are as follows:

export default defineConfig({
    plugins: [vue()],
    server: {
        // Whether to automatically open the application in the browser
        open: true.// Specify which IP address the server should listen on
        host: '127.0.0.1'.// Specify the port number of the development server
        port: 8080./ / agent
        proxy: {
            '/api': {
                target: 'http://127.0.0.1:8888'.changeOrigin: true.rewrite: path= > path.replace('^/api'.' '(}}}});Copy the code

3.3 Build Options

When the system is developed, it must be packaged and released. Vite’s packaged build takes advantage of rollup’s ability. The options for packaged builds are as follows:

export default defineConfig({
    plugins: [vue()],
    build: {
        // Set the browser compatibility target for the final build (default is' modules')
        target: 'es2015'.// Specify the output path. The default is dist
        outDir: 'testOutDir'.// Specify the path to generate static assets
        assetsDir: 'public'.// Specify the size less than which content will be inlined as base64, reducing the number of requests (default 4096, 4KB)
        assetsInlineLimit: 4096.// Whether to generate the source map file after the build. The default is false
        sourcemap: true.// Customize the underlying Rollup configuration (usually not required)
        rollupOptions: {
            // Specify the packaged entry file
            input: {
                default: './index.html'
            },
            // Specify the configuration of file output
            output: {
                // The packaged output format for the block created from the entry point [name] represents the file name and [hash] represents the hash value of the file content
                entryFileNames: 'test/test-[name]-[hash].js'.// Used to name the output name of the shared block created when the code is split
                chunkFileNames: 'js/test-[name]-[hash].js'.// The name of the output static resource, [ext] represents the file extension
                assetFileNames: 'assets/test-[name]-[hash].[ext]'}},// Whether to produce mainfest.json file containing unhashed resource names and hash version mappings
        manifest: true}});Copy the code

Single-page application and multi-page application configuration

The default configuration generated by Vite is a single-page application, but how to configure a multi-page application? It’s worth thinking about, for example, how to configure the following directory structure.

├─ ├─ public │ ├─ Vite - Project ├─.env ├─.├.md ├─ Index.html ├─ Package. json ├─ Public │ ├─ The favicon. Ico ├ ─ SRC │ ├ ─ page1 │ │ ├ ─ index. The HTML │ │ └ ─ SRC │ │ ├ ─ App. Vue │ │ ├ ─ assets │ │ │ └ ─ logo. The PNG │ │ ├ ─ │ ├─ ├─ ├─ vue │ ├─ exercises │ ├─ vue │ ├─ assets │ ├─ │ ├─ ├─ ├─ ├─ class.txt TXT TXT TXT TXT TXT TXT TXT TXT TXT TXTCopy the code

How should the page structure be configured? Let’s take a look.

export default defineConfig({
    plugins: [vue()],
    root: './src'.build: {
        rollupOptions: {
            input: {
                page1: path.resolve(__dirname, './src/page1/index.html'),
                page2: path.resolve(__dirname, './src/page2/index.html'(}}}});Copy the code