Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

When using NPM to run a local project, as the project becomes larger, the time for each project to start will become longer. This article focuses on the HardSourceWebpackPlugin to improve the speed of the project after the second startup, and the solution to hot reload failure after using the plugin

The local environment

Node: v14.16.1 webpack: 4.44.2@vue/CLI: 4.5.11

The plug-in

This plug-in provides caching between modules, which will take normal time on the first build of the project and significantly less time on the second build. The project I am currently using (about 20W lines of code) required about 33 seconds for the second build before using this plug-in, but after using this plug-in, the second build time was reduced to about 13 seconds, increasing the average speed by about 60%.

Plugin details configuration address: portal

  • usenpm i hard-source-webpack-pluginCommand to install the plug-in
  • Import plug-ins in vue.config.js (import other manually configured environments in the corresponding location of the environment)
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')
Copy the code
  • Use in pluginHardSourceWebpackPlugin
chainWebpack(config){
    config
        .when(process.env.NODE_ENV == 'development'.config= > {
                config
                    .plugin('HardSourceWebpackPlugin') .use(HardSourceWebpackPlugin); })},Copy the code

Introduced plugin hot overload does not take effect and workaround

Hot overloading is already integrated with vue-CLI, but it will be disabled when we introduce this plug-in. Here is a screenshot of the official document

I don’t know if you got it here, but I’m a little confused. Follow-up through Issues found clues

Subsequent attempts are often repeated, requiring hot overloading of the plug-inHotModuleReplacementPluginPlaced inHardSourceWebpackPluginCan be solved later.

The final results

In vue. Config. Js import webpack, and behind the HardSourceWebpackPlugin use HotModuleReplacementPlugin

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')
const webpack= require('webpack')

module.exports = {
    chainWebpack(config){
        config
            .when(process.env.NODE_ENV == 'development'.config= > {
                    config
                        .plugin('HardSourceWebpackPlugin')
                        .use(HardSourceWebpackPlugin);
                    config
                        .plugin('hot') .use(webpack.HotModuleReplacementPlugin); }})},Copy the code