About Vite Basics Read my last article # to learn about Vite Basics

1. Advantages and disadvantages of Vite2 construction tool

Traditional tool development environment construction versus Vite:

Traditional tool building:

When starting a development server cold, packager-based startup must first capture and build your entire application before it can be served.

Vite building method:

Vite improves development server startup times by separating the modules in an application into dependencies and source code at the beginning.

Dependencies are mostly pure JavaScript that does not change during development. Some of the larger dependencies, such as component libraries with hundreds of modules, are also costly to handle. Dependencies often exist in multiple modular formats (such as ESM or CommonJS)

Vite will prebuild dependencies using ESBuild. Esbuild is written in Go and is 10-100 times faster than packager prebuilt dependencies written in JavaScript.

The source code usually contains files that are not directly JavaScript, that need to be transformed (such as JSX, CSS, or Vue/Svelte components), and that are often edited. At the same time, not all source code needs to be loaded at the same time (such as routing split-based code modules).

Vite provides the source code as a native ESM. This essentially lets the browser take over some of the packaging: Vite simply converts the source code when the browser requests it and makes it available on demand. Import code dynamically based on the situation, that is, it is processed only when it is actually used on the current screen.

Update the contrast

Update in traditional tools (Webpack) :

Rebuilding the entire package based on a packager startup is inefficient. It’s easy to see why: The rate of updates will plummet as the size of the application increases.

Some packagers’ development servers store the build content in memory, so they only need to deactivate part of the module diagram when the file changes [1], but it still requires an entire rebuild and reload of the page. This is costly, and reloading the page eliminates the current state of the application, so the packager supports dynamic module hot reloading (HMR) : allowing a module to “hot replace” itself without affecting the rest of the page. This greatly improves the development experience — however, in practice we have found that even with the HMR model, the thermal update rate decreases significantly as the size of the application increases.

Vite Update: In Vite, HMR is performed on the native ESM. When editing a file, Vite only needs to precisely deactivate the chain between the edited module and its nearest HMR boundary [1] (most of the time just the module itself), so that HMR is always updated quickly, regardless of the size of the application.

Vite also makes use of HTTP headers to speed up reloading of the entire page (again, making the browser do more for us) : requests from source-source modules are cached through negotiation based on 304 Not Modified, and requests from dependent modules are cached through cache-control: Max -age=31536000,immutable strong cache, so once cached they do not need to be asked again.

Some disadvantages of Vite:

  1. Vite has been around for a very short time, the ecology is not as complete as other build tools, and many problems and concerns have not been exposed
  2. Cutting for code merge is not as powerful as WebPack (micro front, code cutting)

A. resolve B. resolve

Like Webpack, the resolve field indicates how to resolve the module. First, let’s take a look at the common alias setting alias

import { defineConfig, loadEnv } from 'vite' export default ({ mode, command }) => { console.log(loadEnv(mode, process.cwd()).VITE_APP_BASE_PATH, 'base-path') return defineConfig({ resolve: { alias: { '@': Path. The resolve (__dirname, 'SRC'), / / set point ` @ ` ` SRC ` directory}}})}Copy the code

So we can use @ instead of relative paths, we can use @ to introduce components:

import Pagination from '@/components/pagination/index.vue'
Copy the code

3. Import on demand

When we use an Element, we often need to introduce components as needed. In vue-CLI, we use babel-plugin-Component, a plug-in of Babel. Vite has its own plugin-plugin-style-import plugin. First, let’s install it:

npm install vite-plugin-style-import -D
Copy the code

It is then configured in vite.config.js

import styleImport from "vite-plugin-style-import";
export default defineConfig({
  plugins: [
    vue(),
    styleImport({
      libs: [
        {
          libraryName: "element-plus",
          esModule: true,
          ensureStyleFile: true,
          resolveStyle: (name) => {
            return `element-plus/lib/theme-chalk/${name}.css`;
          },
          resolveComponent: (name) => {
            return `element-plus/lib/${name}`;
          }
        }
      ]
    })
  ]
})
Copy the code

Next, if we only want to introduce some components, we can add them in main.js:

import { ElButton, ElSelect } from 'element-plus'

const app = createApp(App)
app.component(ElButton.name, ElButton)
app.component(ElSelect.name, ElSelect)
Copy the code

4. Gzip compression

Plug-in installation

npm install vite-plugin-compression -D

# or yarn
yarn add vite-plugin-compression -D
Copy the code

Usage:

import viteCompression from 'vite-plugin-compression'
import { defineConfig, loadEnv } from 'vite'
export default ({ mode, command }) => {
  return defineConfig({
    plugins: [
      viteCompression()
    ],
  })
}
Copy the code

Five, file packaging analysis

Plug-in installation

npm install rollup-plugin-visualizer -D

# or yarn
yarn add rollup-plugin-visualizer -D
Copy the code

Usage:

import { visualizer } from 'rollup-plugin-visualizer'
import { defineConfig, loadEnv } from 'vite'
export default ({ mode, command }) => {
  return defineConfig({
    build: {
      rollupOptions: {
        plugins: [
          visualizer({ open: true, gzipSize: true })
        ]
      }
    }
  })
}
Copy the code

6. Convert the external import to global variables and package the module to exclude

Plug-in installation

npm install -D rollup-plugin-external-globals

# or yarn
yarn add rollup-plugin-external-globals -D
Copy the code

Usage:

import externalGlobals from 'rollup-plugin-external-globals'
import { defineConfig, loadEnv } from 'vite'
export default ({ mode, command }) => {
  return defineConfig({
    build: {
      rollupOptions: {
        external: ['vue', 'vuex', 'vue-router', 'axios', 'ElementPlus'],
        plugins: [
          externalGlobals({
            vue: 'Vue',
            'element-plus': 'ElementPlus',
            'vue-router': 'VueRouter',
            vuex: 'Vuex',
            axios: 'axios'
          })
        ]
      }
    }
  })
}
Copy the code

Use rollup plugin for vite

In general, a Rollup plugin should only be a Vite plugin as long as it meets the following criteria:

  • The moduleParsed hook is not used.
  • It doesn’t have a strong coupling between the package hook and the output hook.
  • If a Rollup plug-in is significant in the construction phase, only is in the build. RollupOptions. Plugins can be specified.

It is recommended to use the Vite specific plug-in when you are not sure whether it will work:

  • The Vite plug-in should have a semantically clear name prefixed with ite-plugin-.
  • Include the ite-plugin keyword in package.json.
  • Add a section of the plug-in documentation detailing why this plug-in is a Vite specific plug-in (e.g., this plug-in uses Vite specific plug-in hooks).

Eight, hot update

Hot Module replacement, or HMR, is a technology that allows you to update the effects of your code without having to refresh the browser. The key is to establish a connection between the browser and the server. Fortunately, we already have a technology to do this: Websocket protocol, the common HTTP protocol is a short connection, the end of a session will be closed, this obviously can not meet our need to connect the browser and server all the time, while Websocket is a long connection, can keep the browser and server session is not interrupted. Events are used to send data to each other, and Vite also uses WebSocket for hot updates.

The main process of hot update is as follows:

  1. The server listens for file changes based on the watcher, determines the update mode based on the type, and compiles the resource
  2. The client listens for some updated message type through WebSocket
  3. The client receives the resource information and performs the hot update logic based on the message type

❤️ Thank you for reading

  1. If this article helped you, don’t be afraid to give me a thumbs-up. Your thumbs-up are what keeps me going.
  2. Welcome to follow the public number [front-end meditation], you can also scan the code to add my wechat remarks [Group] pull you into the exchange and sharing group, learn and progress together.