The background,

In the old project three years ago, the technology stack was React + Webpack4, which integrated many modules. The project was huge, and every time the code was changed, we had to wait for about 20 seconds. It was really a bit doubtful about life. On the first day I took over the project, I wanted to optimize it if I had the opportunity. With my understanding of the project and adapting to the work pace, I started to optimize the hot loading of the project recently.

Two, webpack4 optimization

Optimizations that have been made

  • DllPlugin
  • Babel-loader sets the cache

Try to optimize

  • react-hot-loader
  • hard-source-webpack-plugin
  • react-refresh

Several schemes have been tried with little effect; Later, when I asked for help for a certain problem, I was treated with Esbuild and Vite by Amway. After seeing the exaggerated data comparison on the esbuild homepage, I tried Vite with a skeptical attitude.

Migrate to Vite

1. Introduction of vite

Vite uses esBuild pre-built dependencies for third-party libraries. Esbuilds are written using Go and are 10-100 times faster than packager pre-built dependencies written in JavaScript. To provide source code in the native ESM way, without the compilation process of Webpack, can be said to be a dimension reduction blow to Webpack…



Chinese reply from webpack team members..

2. Migration procedure

2.1 Create vite.config. js in root directory, complete configuration:


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

function ttt (){}export default defineConfig({
  plugins: [
    reactRefresh(),
    // Handle the ANTD date component to show only today's problems
    antdDayjs({ preset: 'antdv3'})].base: '/'.resolve: {
    extensions: ['.mjs'.'.js'.'.ts'.'.jsx'.'.tsx'.'.json'].alias: [{find: '@src'.replacementXXXX: "}, {find: 'react-native'.replacement: 'react-native-web' },
      { find: '@ant-design/icons/lib/dist'.replacement: '@ant-design/icons/lib/index.es.js'}},optimizeDeps: {
    // exclude: ['bizcharts']
  },
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true}}},server: {
    port: 3000.host: 'localhost'.open: '/'.proxy: {
      '/api': {
        target: 'xxx'.changeOrigin: true}}},define: {
    'process.env': {
      // It is intended to be used only in development environments
      NODE_ENV: 'development'}}});Copy the code

2.2 Copy index.html to the root directory

Add

2.3 Package. json Adds the startup command

  "start:Vite": "Vite"

Now that the Vite configuration has come to an end, you can try to run “start:Vite”: “Vite”, you will find various errors, and start the pit filling journey.

2.4 The development environment is Vite, and webpack compatibility is maintained online

2.4 Let Webpack handle import.meta. GlobEager and import.meta

test: /.(js|mjs|jsx|ts|tsx)$/,
use: [
  { loader: require.resolve('@open-wc/webpack-import-meta-loader')}, {loader: require.resolve('babel-loader'),
    options: {
      presets: ['babel-preset-vite'].plugins: [[require('@babel/plugin-syntax-import-meta']]}}]Copy the code

3. Problems encountered

3.1 Cannot find module ‘worker_threads’  

The node or 12

3.2 Unknown theme type: undefined, name: undefined
alias: {
    '@ant-design/icons/lib/dist': '@ant-design/icons/lib/index.es.js'
},
Copy the code
3.Require is not defined,

If backgroundimage: url (${the require (‘ common/Asset/icon ${item. Index_page}. The SVG ‘)})

You can write a tool method to get pictures

const getImageUrl = imageName= > {
    SRC /utils: SRC /utils: SRC /utils: SRC /utils: SRC /utils /.. /
    return `The ${new URL(`.. /.. /src/${imagePath}`.import.meta.url).href}`;
};
backgroundimage:`url(${getImageUrl(`${item.index_page}.svg`)}) `
Copy the code
3.4 error: No matching export in “node_modules/@antv/util/esm/index.js” for import “max”

@antv/util upgraded to 2.0.17

The requested module ‘XXX’ does not provide an export named ‘xx’

Exports to export

3.6 Failed to fetch Dynamically imported Modules

To switch to the import. Meta. Glob

3.7  process is not defined
// vite.config.js
define: {
  'process.env': {
    NODE_ENV: 'development'}}Copy the code
The date component of 3.8 ANTD shows today only

Vite.config.js Add plugins: [antdDayjs({preset: ‘antdv3’})] (preset parameter is not used for non-V3 versions)

3.9 Import.meta. glob Webpack build error Description
npm install --save-dev babel-preset-vite @babel/plugin-syntax-import-meta 
presets: ['babel-preset-vite'].plugins: ['@babel/plugin-syntax-import-meta']
Copy the code
3.10 Import.meta. Url Webpack build error Description

Add @ the open – wc/webpack – import – meta – loader

3.11 Dynamic require of “xxx. CSS “is not supported

Changed yimi-Form-Components…

// require("antd/lib/table/style/index.css");
import "antd/lib/table/style/index.css"
Copy the code
The requested module ‘/node_modules/.vite/react-intl.js? v=94a2fd86’ does not provide an export named ‘intlShape’

IntlShape: intlShape: intlShape: intlShape: intlShape: intlShape: intlShape: intlShape: intlShape: intlShape: intlShape: intlShape Remove the ‘intlShape’ and start the project..

3.13 the GEThttp://localhost:9021/@id/dayjs/moment net::ERR_ABORTED 404 (Not Found)

Import moment from ‘moment/moment’; Import moment from ‘moment ‘instead; Can be

3.14 After the page is opened, more than 2000 HTTP requests are sent, and it still takes 9s to complete the rendering

I have checked the requested files, most of which are Services files generated by Swagger. Since Services are exported through a file, all services files are referenced when used. I have checked that there are indeed more than 1800 files under Services.

Look at the vite documentation is introduced:

Some packages import their ES module builds to each other as many separate files. For example, Lodash-es has over 600 built-in modules! When we executed import {debounce} from ‘lodash-es’, the browser made over 600 HTTP requests at the same time! Although the server has no problem handling these requests, the large number of requests can cause network congestion on the browser side, causing pages to load very slowly. By pre-building LoDash-es as a module, we only need one HTTP request!

So you can add similar modules to pre-builds, such as services here, as well as translation related ones

  optimizeDeps: {
    include: ['@src/services'.'@src/Locales/zh_CN'.'@src/Locales/en_US']}Copy the code
3.15 Vite always reload, new dependencies.. The prompt

Because of dynamic import, prebuild can continue after the project starts, but instead of manually configuring multiple dependencies with viet.config. js, use the viet-plugin-optimized-persist plug-in to write the configuration to package.json\

// vite.config.ts
import OptimizationPersist from 'vite-plugin-optimize-persist'
import PkgConfig from 'vite-plugin-package-config'

plugins: [
  PkgConfig(),
  OptimizationPersist()
]
Copy the code

Effect of four,

webpack Vite
First startup 45s 20s
Second start 45s 1s
Thermal loading 20s 1s

Five, the summary

The plan is to do some optimization for Webpack, but I tried many methods and got no effect, so IT is better to directly go to Vite, the investment time is about the same (after filling a lot of holes), but the harvest of development experience is extreme.

Six, reference

Play with Webpack and increase your packing speed by 90%

Vite official document

Vue-cli3 VUE2 retains the successful practice of WebPack support for Vite

6 years old project migration vitE2, speed up dozens of times, really fragrant

Vite dynamic import introduces a packaged error solution

How is Rollup compatible with Vite 2.0?