vite packaging configuration (static resource merging and packaging/clearing log/gzip compression/ENV configuration, etc.)

2022/6/2 update

Pass the code of this project, basically everything written in the article is useful, you can clone it to have a look

Download address https://github.com/shinjie1210/vite-config.git --------------------------------- -------------------------------------------------- -----------------------------------------

I was going to follow up on the previous article

The vite+vue3+elementplus tutorial https://mp.csdn.net/mp_blog/creation/editor/122127233 continues to be written, but the content of the article is a bit too much, and the code is too long to look at it.

So I will open another record here. They are all relatively basic configurations. Make a note of them for fear that I will forget the ball.

/*If you see other vite configuration related articles, you can share them in the comment area, or share them with me in private messages. Let's study and study together, thank you*/

Table of contents

1. Merge and package static resources

 2. Static resource file splitting

2.1 Raise the warning threshold for oversized static resources  

2.2 Splitting of super large static resources

3.gzip static resource compression

 4. Clear console and debugger

5. IE is compatible with old versions of chrome

To be continued, the vite configuration code of the current project (a-project) is as follows


1. Merge and package static resources

Let's start writing directly from the content of vite.config in the previous article,

We paste the previous code here,

I don’t know why the previous content is written like this, just click the link and take a look at the vite+vue3+elementplus tutorial (updated to prepare before project deployment and launch) https://mp.csdn.net/mp_blog/creation/editor/122127233

import {
  defineConfig,
  loadEnv
} from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import {
  ElementPlusResolver
} from 'unplugin-vue-components/resolvers'
// https://vitejs.dev/config/
export default defineConfig({
  base: '/aProject/',
  plugins: [vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ]
})

Then the book is continued from the last time, the files packaged by running vite run build directly are very messy, maybe like this

It’s okay if you just write a simple demo, but you can’t write a serious project.

So we need to package static resources and add build settings in defineConfig

build: {
    rollupOptions: {
      output: {
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
      }
    }
  }

 So let's test the effect

npm run build

 It's obviously much neater and more comfortable to look at

 2. Static resource file splitting

Notice:

Other project files are used here as an example,

The project (a-project) used as an example did not refer to any plug-ins, and eleplus was also imported on demand, so there is no way to reproduce the alarm scene.

Mainly introduce the usage here, after the static resources are written, it will be used back to the project (a-project)

Now what we are demonstrating is just a small project. A lot of plug-ins may be introduced in normal projects to realize functions.

When packaging, there will be a warning that the file is too large, such as the project I used as an example

Components such as video\voiceprint\elementplus (not automatically imported on demand) have been introduced , and this happens when packaging

 (!) Some chunks are larger than 500 KiB after minification. Consider:
- Using dynamic import() to code-split the application
- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks
- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.

Call the police if it exceeds 500k, and then there is a Big Mac with more than 1mb here watching you ==

At this point we have two solutions:

2.1 Raise the warning threshold for oversized static resources  

Let's talk about the simple solution first, isn't it more than 500k to call the police?

Then I just increase the alarm limit, so we increase the alarm limit to 1500kb

We add a line of code in the build settings, like this

 build:{
    chunkSizeWarningLimit: 1500,
//其他配置这里就省略了 减少点重复代码长度
  }

Then we run build

 The Big Mac is still there, but no more warnings

But isn't this fucking deceitful? So we're going to use the second method

2.2 Splitting of super large static resources

Still the same, we add the following code in the output setting in the build

 manualChunks(id) {
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString();
          }
        }

The run build file is disassembled again, instead of all the imported js being pasted together to make a giant

 But there are still more than 300 kb of video plug-ins and more than 500 kb of eleplus...so it is very important to introduce eleplus and choose the right plug-ins as needed

3.gzip static resource compression

So large files can't be left alone, we can still process them through gzip compression

First install the plug-in, console input

 npm i vite-plugin-compression -D

Then modify the vite.congfig.js page, import and use it in the plugin

//引入
import viteCompression from 'vite-plugin-compression'
//在plugins配置数组里添加gzip插件
 plugins: [viteCompression({
    verbose: true,
    disable: false,
    threshold: 10240,
    algorithm: 'gzip',
    ext: '.gz',
  })],

run build Run it, the surprise is big, the compression efficiency of large files is gratifying

 4. Clear console and debugger

This step is relatively simple, just add terserOptions configuration in build

terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },

5. IE is compatible with old versions of chrome

First of all, I would like to bless those who still insist on using IE and the old version of chrome____ under unforced circumstances . Are you addicted to using outdated products?

Then compatibility is mainly to install a plug-in, we console input

npm i @vitejs/plugin-legacy -D

Then go to the vite.config.js page to import and use the same

//引入
import legacyPlugin from '@vitejs/plugin-legacy'
//在plugins配置数组里添加legacy插件
 plugins: [legacyPlugin({
      targets: ['chrome 52'], // 需要兼容的目标列表,可以设置多个
      additionalLegacyPolyfills: ['regenerator-runtime/runtime'] // 面向IE11时需要此插件
    })],

Then your code will be compatible with obsolete products

I'm writing here today, I'm too tired to write

To be continued, the vite configuration code of the current project (a-project) is as follows

import {
  defineConfig,
  loadEnv
} from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import viteCompression from 'vite-plugin-compression'
import {
  ElementPlusResolver
} from 'unplugin-vue-components/resolvers'
import legacyPlugin from '@vitejs/plugin-legacy'
export default defineConfig({
  base: '/aProject/',
  plugins: [vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }), viteCompression({ //gzip压缩
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz',
    }), legacyPlugin({
      targets: ['chrome 52'], // 需要兼容的目标列表,可以设置多个
      additionalLegacyPolyfills: ['regenerator-runtime/runtime'] // 面向IE11时需要此插件
    })
  ],
  build: {
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
    // chunkSizeWarningLimit: 1500,大文件报警阈值设置,不建议使用
    rollupOptions: {
      output: { //静态资源分类打包
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        manualChunks(id) { //静态资源分拆打包
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString();
          }
        }
      }
    }
  }
})

Supongo que te gusta

Origin blog.csdn.net/shinjie1210/article/details/122473024
Recomendado
Clasificación