A little bit of vite lore

General introduction

Vite is a front-end development and construction tool developed by the author of VUE Yu Xi. It mainly has the following advantages:

  1. In development mode, use native ESM files without packaging! Traditional Webpack projects, when the project has a certain size and many pages. When devServer is started, it takes a long time. But Vite uses the original ESM files directly and starts development mode almost in a second!
  2. Light weight fast thermal overload. Vite achieves hot update mainly by creating WebSocket to establish communication between the browser and the server, and sends messages to the client by listening to the changes of files. The client will update different files for different operations.
  3. Rich in features: Support TypeScript, JSX, CSS, and so on out of the box
  4. Rollup is used at build time, supporting multiple modes of build, as well as various rollup plug-ins
  5. Vite’s API has full type support

From the above advantages, it can be seen that Vite is mainly composed of the following two parts:

  1. A development server that provides rich built-in features based on native ES modules, such as surprisingly fast module hot update (HMR).

    • For the ES module, you can read: JavaScript Modules
    • Vite has hot Module replacement built into the Vue SFC and React Fast Refresh. There is also an official integration with Preact via @prefresh/vite. When you create an app using create an app via @vitejs/create-app, the selected template will pre-configure these features for you. This saves a significant amount of configuration time for developers compared to WebPack.
  2. A set of build instructions that use Rollup to package your code and that are pre-configured to output highly optimized static resources for production.

    • For Rollup, those who are interested can read: rollupjs

Vite for project construction optimization

  1. Build.csscodesplit Enables/disables CSS code splitting. It is enabled by default. When enabled, the CSS imported in the asynchronous chunk is inlined to the asynchronous chunk itself and inserted when it is loaded. If disabled, all CSS in the entire project will be extracted into a SINGLE CSS file. When our projects are larger, the CSS styles of each module of the project will be relatively independent. If all the styles are packaged into a single file, it makes no sense for a user to browse a page of a large Web application while waiting for all the resources to load. Therefore, enabling this configuration to have the CSS code imported synchronously with the asynchronous chunk speeds up page rendering.

    This function is also available in Webpack, but you need to download the corresponding plug-in and use it with CSS-Loader. Those of you who are interested come over here.

  2. Preload instruction generation. Vite automatically generates < Link rel=” modulePreload “> directives for import chunks and their direct introduction into the packaged HTML. For those of you interested in preloading instructions, go here

    This functionality, which is also available in WebPack, also requires plug-in configuration. Those of you who are interested come over here

  3. Asynchronous Chunk loading optimization. In a ROLLup project, chunks shared by two or more other chunks will usually generate a shared chunk. When combined with dynamic imports, the following scenarios can easily occur

In the non-optimization scenario, when asynchronous Chunk A is imported, the browser will have to request and parse A before it can figure out that it also needs to share Chunk C. This results in extra network roundtrips.

Vite will automatically rewrite the code using A preload step to split the dynamic import calls so that when A is requested, C will be requested at the same time.

C may also have deeper imports, which in unoptimized scenarios will result in more network roundtrips. Vite’s optimizations keep track of all direct imports, regardless of the depth of the import, and completely eliminate unnecessary round-trips.

Webpack also provides the ability to split code into chunks, but unlike Vite’s out-of-the-box loading optimizations, WebPack requires additional configuration. Those of you who are interested come over here.

Configuration Items

Here is a copy of the viet.config.js file from the actual project:

import vue from '@vitejs/plugin-vue'
import eslint from '@rollup/plugin-eslint'
import path from 'path'
import moment from 'moment'

export default {
  mode, // mode, which specifies in the configuration that the serve and build modes will be overridden. It can also be overridden using the command line --mode option.
  plugins: [
    eslint({
      include: '**/*.+(vue|js|jsx|ts|tsx)'.fix: false,}).// The esLint plugin, with the fix option enabled, fixes esLint errors when the project is started or built
    vue(),
  ],
  base: basePath, // Common base path for development or production environment services
  build: {
    terserOptions: {
      compress: {
        drop_console: true.drop_debugger: true.// Remove the debugger and console from the build environment}},chunkSizeWarningLimit: '1000'.// The size of the chunk file that generates the warning
    rollupOptions: {
      // The configuration passed to rollup for the build pattern
      output: {
        manualChunks(id) {
          // The following code will package the qualified file modules into specific chunk files based on the criteria
          // Split the packages in node_modules into separate chunks to facilitate file preloading and cache optimization
          if (id.includes('node_modules') && id.includes('ant-design-vue')) {
            return 'ant-design-vue'
          } else if (id.includes('node_modules') && id.includes('vue')) {
            return 'vue-module'
          } else if (id.includes('node_modules')) {
            return 'other-module'},},},},resolve: {
    alias: {
      '/@src': path.resolve(__dirname, 'src'), // Set the alias}},define: {
    // Define global constant substitution. The string value will be directly used as an expression, so if you need to define a string constant, it needs to be referenced explicitly (e.g., via json.stringify).
    'BUILD_TIME': JSON.stringify(moment().format('YYYY-MM-DD HH:mm:ss')),},optimizeDeps: {
    include: [
      // Packages that are not in the node_modules direct directory will not be prebuilt. Use this option to force linked packages to be prebuilt
      'ant-design-vue/es/date-picker/locale/zh_CN'.'ant-design-vue/es/locale/zh_CN'.'@ant-design-vue/use',]}}Copy the code

The corresponding Vite version and the related plug-in version

{  
  "devDependencies": {
    "@rollup/plugin-eslint": "8.0.1"."@vitejs/plugin-vue": "1.1.0"."vite": "2.3.8."}}Copy the code

other

  1. Note that the configuration items may vary according to the vite version. You can modify it based on errors reported at build time.
  2. There is an analysis of the vite principle of the article, write more detailed. Inside the Vite Principle: How does Utah’s latest title Work? . However, this article was published in May 2020, and Vite has been released from version 1.0 to version 2.0 in nearly a year. Here is the update log. For a more thorough understanding of how Vite works, you can still read the source code of Vite: Portal