preface
Since I finished writing Vite2.x, I wanted to give Vite a try and see how much faster it was locally than Webpack, so I tested it with a larger react project I was working on. This article does not contain the principle of Vite. Please refer to the official documentation of Vite for related introduction, which only records the problems and solutions encountered in the process of transformation.
Open to
The preparatory work
First, install Vite in your project and generate the simplest version, vite.config.js.
//vite.config.js
import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
export default defineConfig({
plugins: [reactRefresh()]
})
Copy the code
Both ite. Config. js and index.html must refer to the entry file in the root path, index.html.
Added the vite start command to package.json.
Ok, the preparation has been completed, now we begin our transformation (potholing) road.
Add basic configuration to vite
First of all, let me start vite with the determination to die, and sure enough, countless errors were reported.
error:fsevents.watch is not a function .
Fix: Delete package.lock.json and yarn.lock and reinstall.
error: [vite:dep-scan] Failed to resolve entry
This is a private NPM package. The reason is that the local library cannot be loaded. You need to modify the module property of the library’s package.json.
The module attribute is changed to the correct path, and the error is resolved.
Added CSS style preprocessor
Sass and some custom configurations
//vite.config.js
import autoprefixer from 'autoprefixer'
import postcssFlexbugsFixes from 'postcss-flexbugs-fixes'
import postcssPresetEnv from 'postcss-preset-env'
const loder_presetEnv=postcssPresetEnv({
autoprefixer: {
flexbox: 'no-2009',},stage: 3,})export default defineConfig({
/ /...
css: {
modules: {scopeBehaviour:'local'
},
postcss: {plugins:[
autoprefixer,
postcssFlexbugsFixes,
loder_presetEnv
]
},
preprocessorOptions: {
less: {
javascriptEnabled: true,},scss: {
// Add SCSS global variables to the end of the import path;
additionalData: `@import "./src/common/styles/base.scss"; `,}}},//....
});
Copy the code
import styles from './index.module.scss'
<div className={styles.root}>
</div>
Copy the code
If the project style is modules, you must add css.modules to the ite. Config and change all.scss to.module.scss.
Change the global style file suffix by writing a small rename script.
*/ const glob = require('glob') const fs = require('fs'); const files = glob.sync('src/**/*.scss') files.forEach(oldPath => { const newPath = oldPath.replace('.scss','.module.scss') fs.rename(oldPath, newPath, (err) => { if (err) { console.log('err',oldPath) } }) })Copy the code
Start the project again and find that some of the changed global theme colors are gone. Add the global theme configuration.
//vite.config.js less: {// Remove the lessOptions level of the direct configuration option. modifyVars: { 'primary-color': '#19B5A5', 'link-color': '#19B5A5', 'border-color': '#E0E0E0', 'border-radius-base': '2px', 'success-color': '#19B5A5', '#faad14', // warning color' error-color': '#f5222d', // error color}, javascriptEnabled: true,},Copy the code
For details, see less configuration items.
The style is too large after packaging, change it to ANTD load on demand.
Annotate the antD styles introduced globally.
// import 'antd/dist/antd.less'
Copy the code
Added antD load on demand plug-in
npm i vite-plugin-imp -D
Copy the code
//vite.config.js
import vitePluginImp from 'vite-plugin-imp'
export default defineConfig({
//.....
plugins: [
reactRefresh(),
vitePluginImp({
libList: [
{
libName: "antd",
style: (name) => `antd/es/${name}/style/`,
},
],
})
]
});
Copy the code
After loading on demand packaging effect is very nice.
Now that the style changes are done, let’s move on to other issues.
Some of the environment variables that WebPack originally injected are gone
Vite has its own environment variable configuration. address
To customize the location of the vite configuration file, set envDir:’./config’ in ite. Front-end file to obtain the system configuration directly import.meta-env.vite_xxx, very convenient to have.
In vite.config.js, you can’t get the configuration of env directly by import.meta.env.vite_xxx. How can we distinguish between local and production environment to load different vite plug-ins?
Don’t worry, vite’s clever elder brother in the Issuse has a solution.
The compressed image
Project packaging needs to optimize the point vite will give you tips, but how the project will have such a large picture _(:зゝ∠), compress the picture of a plug-in.
npm i vite-plugin-imagemin -D
Copy the code
//vite.config.js
import viteImagemin from 'vite-plugin-imagemin';
//....
plugins: [
//....
viteImagemin({
gifsicle: {
optimizationLevel: 7.interlaced: false,},optipng: {
optimizationLevel: 7,},mozjpeg: {
quality: 20,},pngquant: {
quality: [0.8.0.9].speed: 4,},svgo: {
plugins: [{name: 'removeViewBox'}, {name: 'removeEmptyAttrs'.active: false},],},}),],Copy the code
The effect is obvious.
Vite plugin community address github.com/vitejs/awes… , the plug-in is very full, you can choose according to their own optimization needs.
Vite vs. Webpack time
The startup time
Webpack startup time
Vite startup time
webpack HMR
Vite module hot update is around 100 ~ 200ms, in terms of hot update, Webpack is completely beat, the more modules the bigger the gap. Vite serves source code as a native ESM, simply converting the source code when the browser requests it and returning the converted source code. In this way, the implementation of Vite HMR is simpler and faster than the HRM implementation of WebPack.
Webpack packaging time
Vite packing time
conclusion
Vite has unmatched advantages when it comes to startup and hot updates.
After all, vite’s current community ecology is not as complete as Webpack, and project migration should be considered according to the actual situation and potential risks.
Look forward to further expansion of vite community and influence.
In the end,
Point a praise