The background that

Webpack4 + React-dev-utils was used as scaffolding for several old React projects of the company. With the development of the project and the iteration of requirements, the project started more and more slowly. Rough data are as follows:

The module number The command The elapsed time
4535 npm start 30 – 60s
4535 npm run build 5- 10min

As the project automation deployment runs the pipeline every time, the dependencies have to be reinstalled and packaged, and the total time is about 7-10 minutes! Each project launch and release is a pain in the neck for the team! For this high frequency standardized operation, it is necessary to go a little faster! Some time ago, I tried Vite on a new project. Both the startup speed and the packaging speed are surprisingly fast. The rough data is as follows:

The module number The command The elapsed time
4535 npm start 3-3.5 s
4535 npm run build 21 – 55s

steps

  1. Move public/index.html to the project root directory and remove %PUBLIC_URL% from the file
  2. Change the SRC /index.js entry file to SRC /main.jsx and import it in the index.html file
  <script type="module" src="/src/main.jsx"></script>
Copy the code
  1. Clean up package.json, remove unnecessary dependencies such as esLint, Babel, Webpack, various loaders and plugins, and modify scripts and devDependencies:
"devDependencies": {
    "less": "^ 3.11.1." "."@vitejs/plugin-react-refresh": "^ 1.3.1." "."antd-dayjs-vite-plugin": "^ 1.1.4." ".// For a project, do not use ant-design and moment
    "tslib": "^ 2.3.0." "."vite": "^" 2.4.2."vite-plugin-cesium": "^ 1.2.5." " // If you don't use cesium for your project, don't add cesium
  },
  "scripts": {
    "dev": "vite"."build": "vite build"."serve": "vite preview"
  },
Copy the code
  1. Use the npkill tool to delete the node_modules folder, delete yarn.lock package-lock.json, and reinstall the dependencies

  2. Delete the Config/scripts folder, which contains webPack configuration and startup scripts, and skip this step if your project does not have one

  3. Create a new configuration file named vite.config.js in the root directory and post my configuration for reference:

import { defineConfig } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
import antdDayjs from 'antd-dayjs-vite-plugin';
import cesium from 'vite-plugin-cesium';
import analyze from 'rollup-plugin-analyzer';

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        reactRefresh(),
        cesium(),
        antdDayjs(),
        analyze({   // User analysis package size and number
            summaryOnly: true.limit: 10.//}),].base: '/'.resolve: {
        extensions: ['.mjs'.'.js'.'.ts'.'.jsx'.'.tsx'.'.json'].alias: [{ find: '@ /'.replacement: '/src/'}],},build: {
        outDir: 'build'.minify: 'terser'.// boolean | 'terser' | 'esbuild'
    },
    server: {
        port: 9021.host: 'localhost'.open: '/'.proxy: {
            '/uniauth': {
                target: 'http://192.168.1.211:30114'.changeOrigin: true.rewrite: (path) = > path.replace(/^\/uniauth/.' '),},},},});Copy the code
  1. You can use it nownpm run devThe project is started, but you may encounter the following problem!

Obviously, all files that contain JSX syntax must end in EITHER JSX or TSX. To make this easier, I wrote a simple vite plug-in to handle this.

// rename.plugin.js
const path = require('path');
const fs = require('fs');
export default function myPlugin() {
    return {
        name: 'rename-plugin'.transform(code, id) {
            let fullPath = path.join(__dirname, 'src/');
            if (
                /<([A-Z>]|div|span)/g.test(code) &&
                id.startsWith(fullPath) &&
                id.endsWith('.js')
            ) {
                fs.rename(id, id + 'x'.function (err) {
                    if (err === null) {
                        console.log('Rename successful %s', id + 'x'); }});return{ code, }; }}}; }// Using plugins is easy. Just import the plugins in vite.config.js and call them in plugins
import renamePlugin from './rename.plugin';
// vite.config.js omit part of the code
plugins: [
    renamePlugin(),
    reactRefresh(),
    cesium(),
    antdDayjs(),
    analyze({   // User analysis package size and number
        summaryOnly: true.limit: 10.//}),]Copy the code

Once the configuration is complete, build again to complete the renaming. When you are done using the plugin, remember to disable it

  1. Because vite does not supportrequire()Import, you need to find all the require functions in your project and manually modify them if you use themrequire.contextImporting multiple files at a time, you also need to replace them with vite syntax. For reference:
let modules = import.meta.globEager(
    '/src/assets/map/icons/water_level{0.. 9}.png'
);
const water_levels = [];
for (let [key, val] of Object.entries(modules)) {
    water_levels.push(val.default);
}
Copy the code
  1. Some projects use environment variables such as process.env.node_env === ‘development’, which also needs to be modified. Please refer to the vite documentation for details

  2. If your project uses less and uses a url such as: URL (‘~@/assets/fonts/youshe.ttf’), use VScode search and replace with @

Write in the back

The above ten steps are based on our internal project. If your project is a Vue project, these steps may not be appropriate for you, but they are still useful

Today to share here, if you have a daily maintenance, slow old project, quickly act up, feel vite to bring you the experience of speed ~

I am Xiaoxi in Wuhan, if you read my article is helpful to you, remember to like, collect ~❤️❤️