Use webpack5 to build VUE2 project

The five cores of webpack

  1. entry: Instructs Webpack which file to start packaging from
  2. Output: Instructs Webpack where to output the packaged files, how to name them, etc.
  3. Loader: webpack itself can only handle js, json and other resources. Other resources need to be parsed by loader.
  4. plugins: extend the functionality of Webpack
  5. mode (mode) mainly consists of two modes: development mode (development) and production mode (production)
    Note: This article uses yarn packaging

Initialization

  1. To create a project, you need to initialize the file first: npm init -y, which will generate the package.json project description file (ps: if you don’t add -y, you will need to enter the project name, etc., and adding -y will automatically generate it)

Install webpack

  1. yarn add webpack webpack-merge webpack-cli -d –save
  • -D is equivalent to –save-dev, required dependencies in the development environment; -S is equivalent to –save, required dependencies in the production environment
  • webpack-merge is used to merge webpack configuration files. For example, a general project has three webpack configuration files, a basic one for packaging image styles, etc., one for the production environment and one for the development environment. The development environment needs to incorporate the basic configuration files and then export them.
  • webpack-cli allows you to call webpack from the command line. After executing the command, node_modules (which stores the packages downloaded and installed by the node package management tool) and package-lock.json (this file is designed to track the status of each installed software package) will be generated. Exact version so that the product can be 100% replicated in the same way)

Initialize directories and files

  1. Create new folders and files
  2. Create the basic configuration file for writing webpack, webpack.common.js
const path = require("path"); // Reference path module
module.exports = (env) => {<!-- -->
  // Entry file
  return {<!-- -->
    entry: "./src/index.js",
    output: {<!-- -->
      // Output file name
      filename: "[name].js",
      //The output path is an absolute path (import path module) This is done using node
      path: path.resolve(__dirname, "../dist"),
    },
  };
};
  1. Create a configuration file for writing production environment, webpack.prod.js
const {<!-- --> merge } = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = (env) =>{<!-- -->
   let pro_config = {<!-- -->
     mode:'production',
   };
   return merge(common(env),pro_config); //Merge configuration
}
  1. Add build in package.json file
"scripts": {<!-- -->
  "build": "webpack --config build/webpack.prod.js --mode production",
  "test": "echo "Error: no test specified" & amp; & amp; exit 1"
},
  1. Entering npm run build will execute the webpack.prod.js file. In the prod configuration file, the configuration in webpack.common.js will also be executed with the help of the merge plug-in to produce new files.

Configure the plug-ins you need to use

  1. HtmlWebpackPlugin allows packaged JS to automatically import html files
//...
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = (env) => {<!-- -->
  // Entry file
  return {<!-- -->
    //...
    plugins: [
      new HtmlWebpackPlugin({<!-- -->
        template: path.join(__dirname, "../public/index.html"),
        filename: "index.html", //Output file name
      }),
    ],
  };
};
  1. After configuration, npm run build, and then check the index.html under the dist directory, you can find that the packaged file has been automatically introduced.
  2. ES6 syntax conversion babel-loader, install babel core, corresponding loader and preset environment
  • Install dependencies: yarn add @babel/core babel-loader @babel/preset-env -d –save
  • Add rules to webpack.common.js
//...
      module: {<!-- -->
      rules: [
        {<!-- -->
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: {<!-- -->
            loader: "babel-loader",
            options: {<!-- -->
              presets: ["@babel/preset-env"],
            },
          },
        },
      ],
    },
  1. For style processing, install css and less loaders (if scss, download the scss loader). If less/scss is used in the project, it also needs to be configured.
    • Install dependencies: yarn add style-loader css-loader less less-loader -d –save
    • Add in webpack.common.js rules
//..
const HtmlWebpackPlugin = require('html-webpack-plugin');
 
module.exports = (env) => {<!-- -->
return{<!-- -->
//...
    module: {<!-- -->
      rules: [
        {<!-- -->
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: {<!-- -->
            loader: 'babel-loader',
            options: {<!-- -->
              presets: ['@babel/preset-env'],
            },
          },
        },
        {<!-- -->
          test: /\.(les|cs)s$/,
          use:[
            {<!-- -->loader:'style-loader',options:{<!-- -->}},
            {<!-- -->loader:'css-loader',options:{<!-- -->}},
            {<!-- -->loader:'less-loader',options:{<!-- -->}},
          ]
        },
      ],
    },
}
}

ps: The loading order of multiple loaders is from bottom to top and from left to right. The order here must not be wrong.

So far, the three major components of the front-end, HTMl, JS and CSS, have been processed and the basic conditions for a web page have been completed. However, these are far from enough. We need to continue to improve them next.

Static resources/vue3/ts/code specifications/multi-environment and other configurations can be viewed in the browser index.html. The page can be displayed normally, but each modification needs to be refreshed manually. In order to solve this problem, you can install the local service DevServer

Local service DevServer webpack-dev-server

  1. Installation dependencies: yarn add webpack-dev-server -d to implement local development server
  2. Modify relevant configurations in webpack.dev.js
const {<!-- --> merge } = require("webpack-merge");
const common = require("./webpack.common.js");
const path = require("path"); // Reference path module
module.exports = (env) => {<!-- -->
  //...
  let dev_config = {<!-- -->
    mode: "development",
    devServer: {<!-- -->
        static: {<!-- -->
            directory: path.join(__dirname, '../dist'),
        },
        compress: true,
        port: 8080,
        open:"http://localhost:8080",//Open the specified window
        // proxy: { //Proxy is very important in front-end and back-end joint development. It forwards front-end requests to the target server.
        // "/api": {<!-- -->
        // target: "http://www.xxx.com:8080/api", // Call the backend data
        // secure: true, // If it is an https interface, you need to configure this parameter
        // changeOrigin: true, //Whether to enable gzip compression for each static file
        // pathRewrite: { "^/finchinaAPP": "" },
        // },
        // },
    },
  };

  return merge(common(env), dev_config); //Merge configuration
};
  1. Modify package.json to add scripts and call webpack-dev-server through CLI
 "scripts": {<!-- -->
    "build": "webpack --config build/webpack.prod.js --mode production",
    "serve": "npx webpack serve --config build/webpack.dev.js --mode development",
    "dev": "webpack --mode development",
    "test": "echo "Error: no test specified" & amp; & amp; exit 1"
  },

vue-loader

  1. vue-loader converts the vue code so that the browser can recognize it
  2. Installation dependencies: yarn add -D vue-loader vue-template-compiler vue-style-loader –save (Note: Vue2 does not support vue-loader 16+ or above)
  3. Configure webpack.common.js: One is to introduce vue-loader and the vueLoaderPugin plug-in in plugins; the other is to use vue-style-loader instead of style-loader
const {<!-- --> VueLoaderPlugin } = require('vue-loader')
 
module.exports = {<!-- -->
  module: {<!-- -->
    rules: [
      // ...
      {<!-- -->
        test: /\.vue$/,
        loader: 'vue-loader'
      },
         {<!-- -->
          test: /\.(les|cs)s$/,
          use: [
            {<!-- --> loader: 'vue-style-loader', options: {<!-- -->} },
            {<!-- --> loader: 'css-loader', options: {<!-- -->} },
            {<!-- --> loader: 'less-loader', options: {<!-- -->} },
          ],
        },
    ]
  },
  plugins: [
  //...
    new VueLoaderPlugin()
  ]
}
  1. Introduce vue into the entry file index.js
import Vue from 'vue';
import App from './App.vue'

new Vue({<!-- -->
  el: '#app',
  render: h => h(App)
})
  1. Write App.vue code
<template>
  <div>this is App {<!-- -->{<!-- -->name}}</div>
</template>

<script>
export default {<!-- -->
  name: 'App',
  data() {<!-- -->
    return {<!-- -->
      name: 'Handmade VUE'
    }
  }
}
</script>
  1. At this point, npm run serve or yarn serve can start the vue project.