Some time ago, I accepted an old project, which is not old. The project has been being done, but no one has done the dependency upgrade. Keep using the old version for two or three years. After taking over always puzzling problems appear, make the mentality of collapse, in the familiar with a period of time, slowly adopt the most conservative component writing method. Fulfill this requirement.

While the function is finished in advance, the test bug is almost fixed, and there is still some time before the release, SO I want to pull a new copy version and do an update locally. Record the problems encountered in this dependency upgrade and the solutions.

The current project is a VUE project without the use of VUE-CLI scaffolding. The step-up strategy is used here, and the main priority is to rely on upgrades.

NPM version

My current NPM version:

$ npm -v
7.19.1
Copy the code

Vue version upgrade

The version in the project is V2.5.2, and we upgraded to the latest version of VUE2, V2.6.14

With big releases, it is necessary to keep up to date, some potential problem fixes, new features, etc.

$ npm update vue
Copy the code

There is a conflict between the current [email protected] version and the component library uxcool(internal) dependencies echart@3.

Ok, since there is a problem, then follow the instructions to solve the problem.

  • --forceForcibly pull the latest version of the current installation package, regardless of the existing local copy.
  • --legacy-peer-depsNPM uses a secure policy to deal with the different versions of dependencies.

There are rules that the NPM installation depends on. Let’s not go into too much detail (:dog: I don’t understand either).

At least you can see that this does not have anything to do with upgrading the VUE version. You can install the specified version directly to avoid dependency conflict detection during the update

$NPM install [email protected]
Copy the code

There is no error, the version in package.json is up to date, and there is no problem with the project starting.

Webpack upgrade

Upgrade webPack version v3.6.0 to stable version WebPack4V4.46.0

$NPM install [email protected]
Copy the code

There is a dependency conflict, extract-text-webpack-plugin, HTML -webpack-plugin, webpack-dev-server rely on webpack3, install error, uninstall these packages first, then reinstall.

$ npm remove extract-text-webpack-plugin html-webpack-plugin webpack-dev-server
Copy the code

Do not know which packages will affect the installation of Webpack, directly install according to the error prompt, remove the affected dependency packages.

After successful installation, install the dependencies that were previously written in sequence.

Webpack dev – server upgrade

The current version is V2.9.1, and the latest version is V3.11.2

$ npm install webpack-dev-server --save-dev
Copy the code

NPM run dev cannot be started. Webpack – CLI and webpack need to be installed.

Webpack-cli provides some default configurations and commands commonly used in development.

$ npm install --save-dev webpack-cli
Copy the code

When rebooting, an error was reported saying the module webpack-cli/bin/config-yargs could not be found

Then I started to look for a solution, and finally I found that it was due to the webpack-CLI version update problem, and I also saw the solution of this problem in the Github issue.

  • You can lower the version. I installedv4.7.2I can go down to v3
  • The start command is no longerwebpack-dev-server, the use ofwebpack serve

I just used the second one, modify package.json

{
  "scripts": {-"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
+        "dev": "webpack serve --inline --progress --config build/webpack.dev.conf.js",}}Copy the code

Okay, there is no error in startup.

Extract text — webpack – plugin upgrade

This dependency is used to extract the contents of multiple files into a single file.

In this project, it is used to separate CSS from components, packaging CSS styles from multiple components into a single file, thereby reducing the number of requests for static resources.

To upgrade to webpack4, the mini-css-extract-plugin is recommended

Modify the WebPack section of the configuration. Install the mini-css-extract-plugin, the latest version is v2.1.0, install error, need webpackv5.0.0, so specify version v1.6.2

$NPM install - save - dev [email protected]
Copy the code

There are definitely some advantages to dealing with CSS splitting only in production:

  • Asynchronous loading
  • Are more likely to use
  • No double compilation
  • Deal only with CSS

Modify the configuration file, search globally where the component is used, and make changes:

// const ExtractTextPlugin = require('extract-text-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")

module.exports = {
  // ...
  plugins: [-new ExtractTextPlugin({
-      filename: utils.assetsPath('css/[name].css? v=' + utils.staticVersion()),      
-    }),
    new MiniCssExtractPlugin({
      filename: utils.assetsPath('css/[name].css? v=' + utils.staticVersion()),
      chunkFilename: 'css/[id].css',]}})Copy the code

Extract -text-webpack-plugin for loader configuration

// Utility classes handle rule definitions util.js in multiple environments
/ /... Omit other code
if (options.extract) {
-    return ExtractTextPlugin.extract({
-       use: loaders,
-       fallback: 'vue-style-loader'-}) +return [MiniCssExtractPlugin.loader].concat(loaders)
  } else {
    return ['vue-style-loader'].concat(loaders)
  }
Copy the code
HTML – webpack – plugin upgrade

The current project version is V2.30.1. Upgrade webPack4 to v4.5.2

$ npm i --save-dev html-webpack-plugin@4
Copy the code

Some configurations that need to be adjusted to produce compile-time configurations:

module.exports = {
	plugins: [
      new HtmlWebpackPlugin({
        // ...
        minify: {               // 
          removeComments: true.collapseWhitespace: true.removeAttributeQuotes: true
        },
-        chunksSortMode: 'dependency',
+        chunksSortMode: 'auto'.// Change the optional value to None Auto Manual]}}),Copy the code
Deprecated Webpack plugin
  • webpack.NamedModulesPlugin()Identify modules for easy debugging
  • new webpack.NoEmitOnErrorsPlugin() Error packages are not generated when there are errors.
  • new webpack.optimize.ModuleConcatenationPlugin()Precompiled module – production configuration

Now use configuration items instead:

module.exports = {
  optimization: {
    noEmitOnErrors: true.namedModules: true.concatenateModules:true,}}Copy the code

Vue – loader upgrade

After processing webPack-related dependencies, start the project and compile normally. Error at last

The current project version is V13.3.0, upgraded to V14.2.4

$NPM install - save - dev [email protected]
Copy the code

Restart, successfully started,

Babel upgrade

Include babel-loader \ babel-core \ babel-preset-env to remove old dependency packages

Install a new dependency package:

  • babel-loader
  • @babel/core
  • @babel/preset-env
# remove
$ npm remove babel-loader babel-core babel-preset-env
# add
$ npm install babel-loader @babel/core @babel/preset-env --save-dev
Copy the code

After the installation is complete, modify webpack.base.config.js

module.exports = {
  module: {
        rules: [{test: /\.js$/,
-               loader: 'babel-loader'.include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')],
+               use:{
+                    loader:'babel-loader',
+                    options:{
+                        presets:[
+                            ['@babel/preset-env', { targets: "defaults"}] +] +} +}},]}}Copy the code

An error is reported after startup, we have uninstalled babel-preset-env and installed @babel/preset-env. But babel-loader’s dependency is not read.

.babelrcConfiguration changes

Need to modify. Babelrc file as follows, solve the previous problem.

{
  "presets": -"env", {+ ["@babel/preset-env", {
      "modules": false."targets": {
        "browsers": ["1%" >."last 2 versions"."not ie <= 8"]}}],"stage-2"]."plugins": ["transform-vue-jsx"."transform-runtime"]}Copy the code

An error was reported after the restart

This made me realize that all Babel related components could be renamed with @babel prefix, and I checked them one by one to upgrade them all

  • @babel/plugin-syntax-jsx
  • @babel/plugin-transform-runtime
  • @babel/preset-stage-2
# remove
$ npm remove babel-plugin-syntax-jsx babel-plugin-transform-runtime babel-preset-stage-2
# add
$ npm install @babel/plugin-syntax-jsx @babel/plugin-transform-runtime @babel/preset-stage-2 --save-dev
Copy the code

Modify babelrc.

{
  "presets": [["@babel/preset-env", {
      "modules": false."targets": {
        "browsers": ["1%" >."last 2 versions"."not ie <= 8"-]}}]"stage-2"
    "@babel/preset-stage-2"] -"plugins": ["transform-vue-jsx"."transform-runtime"]
+  "plugins": [
  	"transform-vue-jsx"."@babel/plugin-transform-runtime"."@babel/plugin-syntax-jsx"]}Copy the code

Found on startup that the @babel/preset-stage-2 setting is different, follow the prompts

@babel/preset-stage-2Configuration to adjust

Unlike previous versions, the latest Babel has scrapped all presets and has to be installed itself

$ npm install @babel/plugin-proposal-decorators @babel/plugin-proposal-function-sent @babel/plugin-proposal-export-namespace-from @babel/plugin-proposal-numeric-separator @babel/plugin-proposal-throw-expressions --save-dev
Copy the code

Modify. Babelrc, specific is according to the official document to increase the configuration

{
  "presets": [["@babel/preset-env", {
      "modules": false."targets": {
        "browsers": ["1%" >."last 2 versions"."not ie <= 8"-]}}]"stage-2"
-    "@babel/preset-stage-2"] -"plugins": ["transform-vue-jsx"."transform-runtime"]
+  "plugins": [
      "transform-vue-jsx"."@babel/plugin-transform-runtime"."@babel/plugin-syntax-jsx"["@babel/plugin-proposal-decorators", { "legacy": true}]."@babel/plugin-proposal-function-sent"."@babel/plugin-proposal-export-namespace-from"."@babel/plugin-proposal-numeric-separator"."@babel/plugin-proposal-throw-expressions"]}Copy the code

No errors were reported after startup.

babel-plugin-transform-vue-jsxupgrade

The current version of the project is V3.7.0 and Babel 7 needs to be upgraded to V4.0.1

$NPM install [email protected] - save - dev
Copy the code

The reason for upgrading this is because after compiling, the test deployment, the error h undefined, I thought that I might not parse JSX syntax.

Compile the project

After testing all functions of the upgrade, there is no problem found temporarily. Test compilation:

CommonsChunkPlugin

Webpackage 4 has been removed and splitChunksPlugin is used instead. It is used to split common modules and facilitate cache loading, thus improving page loading speed.

Error prompt is also very obvious, according to the official website documentation, reconfigure the next

SplitChunksPlugin has default configuration behavior to improve page loading performance.

  • The shared module comes fromnode_modulesfolder
  • Split package larger than 30KB before compression
  • The number of parallel requests loaded on demand is less than or equal to 5
  • The maximum parallel request for initial page loading is less than or equal to 3
module.exports = {
    optimization: {splitChunks: {chunks: 'async'.// Define which type of module is optimized for all Async initial
          minSize: 30000.maxSize: 0.minChunks: 1.maxAsyncRequests: 5.maxInitialRequests: 3.automaticNameDelimiter: '~'.name: true.cacheGroups: {
            vendors: {
              test: /[\\/]node_modules[\\/]/,
              priority: -10
            },
            default: {
              minChunks: 2.priority: -20.reuseExistingChunk: true
            }
          }
        }
   }
}
Copy the code
vue-style-loader

Similar to style-loader, vue-style-loader is no longer needed after the mini-css-extract-plugin is introduced to compile the configuration items

An error is reported if vue-style-loader is introduced at compile time

// ...
if (options.extract) {
     return [MiniCssExtractPlugin.loader,'vue-style-loader'].concat(loaders)
  } else {
    return ['vue-style-loader'].concat(loaders)
  }
Copy the code

The example on the website illustrates this point,

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
constdevMode = process.env.NODE_ENV ! = ='production';

module.exports = {
  module: {
    rules: [{test: /\.(sa|sc|c)ss$/,
        use: [
          devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
          'css-loader'.'postcss-loader'.'sass-loader',],},],},plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]),
};
Copy the code

Configure Eslint and husky

To standardize your code format and git commit format, configure Eslint and husky.

Eslint installation

I’ve configured a project before, so I’m going to take care of this one pretty quickly.

#The installation
$ npm install eslint --save-dev
#Initialize the configuration file
$ npx eslint --init
Copy the code

After executing the second command, an interactive window appears that lets you select some options that are appropriate for your project. Finally install the required dependencies

  • eslint-plugin-vue
  • eslint-config-standard
  • eslint-plugin-import
  • eslint-plugin-node
  • eslint-plugin-promise

After the installation, the configuration file.eslintrc.js is automatically generated

module.exports = {
  env: {
    browser: true.es2021: true
  },
  extends: [
    'plugin:vue/essential'.'standard'].parserOptions: {
    ecmaVersion: 12.sourceType: 'module'
  },
  plugins: [
    'vue'].rules: {}}Copy the code

Modify package.json to add a script that detects all files in the SRC/directory and automatically fixes them.

{
  "scripts": {
        "lint":"npx eslint src/ --fix"}},Copy the code

NPX esLint SRC / 2974 errors, with arguments –fix only 41 errors left.

Husky installation

If you have esLint configured, you can commit without fixing errors. If husky is installed, you can commit before committing.

Configuration installation:

$ npm install husky --save-dev
Copy the code

Initialization is required once the installation is complete

#A script is generated in package.json
$ npm set-script prepare "husky install"
#Execute the script
$ npm run prepare
Copy the code

After execution, you can see that the.husky/ folder was generated in the project directory and initialized successfully.

Creating a COMMIT hook

$ npx husky add .husky/pre-commit "npm run lint"
#Add to Git hook
$ git add .husky/pre-commit 
Copy the code

A pre-commit file is generated in the.husky/ directory and can be opened for editing.

The file cannot be submitted. The file cannot be submitted. The file cannot be submitted.

One problem is that all files under SRC are checked each time, which can be troublesome. In practice, we only want to check the files we have changed.

Installation dependencies Lint-staged:

$ npm install --save-dev lint-staged
Copy the code

Create the configuration file lint-lanterns.config.js

/** * git file format */
 module.exports = {
    "src/**/*.{js,ts,vue,tsx,jsx}": "eslint --fix"};Copy the code

You can add a script to package.json

{
  "scripts": {
    "lint-staged": "npx lint-staged --config lint-staged.config.js",}}Copy the code

Husky /pre-commit Command executed

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

- npm run lint
+ npm run lint-staged
Copy the code
Commitlint configuration

Configure the code format verification, everyone can be happy to submit code. Another problem is the format of the Commit message.

Format our Commit Message using @commitlint/cli.

Install dependencies and use shared specifications. [commitlint/config-angular]

$ npm install --save-dev @commitlint/cli @commitlint/config-angular
Copy the code

Generated git hook:

$ npx husky add .husky/commit-msg "npm run commitlint"
Copy the code

Define package.json scripts

{
  "scripts": {
        "commitlint": "npx commitlint -e",}}Copy the code

Create a configuration file to configure commitlint.config.js

/** * git push */
module.exports = {
    extends: ['@commitlint/config-angular'].rules: {"type-enum": [2."always"["feat"."fix"."docs"."style"."refactor"."test"."chore"]]}}Copy the code

Modify the script to point to the configuration file

npx commitlint -e --config commitlint.config.js
Copy the code

The basic and important dependencies are upgraded, and the rest are business component-related dependencies that need to be evaluated to see if they can be upgraded. This will involve modifying the code, so don’t upgrade for the time being.