Plugins can do things for you when WebPack runs to a certain point, much like life cycle functions in React and Vue.

HtmlWebpackPlugin

  1. The installation
npm install --save-dev html-webpack-plugin
Copy the code
  1. function

An HTML file will be automatically generated at this moment after packaging, and the JS generated by packaging will be automatically introduced into the HTML file

  1. use
// const HtmlWebpackPlugin = require('html-webpack-plugin')
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html'  //'src/index.html'Set template})],Copy the code

CleanWebpackPlugin

  1. The installation
npm install --save-dev clean-webpack-plugin
Copy the code
  1. function

Deletes the specified package directory before the project is packaged

  1. use
  const { CleanWebpackPlugin } = require('clean-webpack-plugin')
  plugins: [
    new CleanWebpackPlugin()
  ]
Copy the code

sourceMap

SourceMap is a mapping that maps compiled files to source files to find errors in code

  1. use
devtool: 'soucre-map'
Copy the code
  1. Different devtool values correspond to different packaging speeds and effects. Best practices are as follows:
  • Configuration in the development environment
mode: 'development',
devtool: 'cheap-module-eval-source-map'
Copy the code
  • Online environment: Devtool is not usually required, but to locate online problems, you can configure:
mode: 'production',
devtool: 'cheap-module-source-map'
Copy the code
  • Interview question: How does sourceMap work??

If you want to modify the code every time, you can automatically package it without manually entering the specified command on the command line

Method 1: Modify the scripts of package.json

  "scripts": {
    "watch": "webpack --watch"
  },
Copy the code

This approach is not good enough if you want to automate packaging while automatically opening the browser and emulating some of the features on the server

Method two uses WebpackDevServer

  1. The installationwebpack-dev-server
npm install webpack-dev-server -D
Copy the code
  1. Add the webpack configuration and make the following changes in webpack.config.js
  devServer: {
    contentBase: './dist'
  }
Copy the code
  1. Modify packge.json to add the scrits content
  "scripts": {
    "watch": "webpack --watch"."start": "webpack-dev-server"
  },
Copy the code
  1. The NPM run start command will automatically compile the package and refresh the page every time the source file is modified

  2. If you do not want to manually access port 8080, run the NPM run start command to automatically open the browser

  devServer: {
    contentBase: './dist',
    open:true
  }
Copy the code

Why start a local service using WebpackDevServer?

Sometimes we need to make Ajax requests in the front end. Local direct access to the HTML page is opened through the File protocol, so ajax requests cannot be sent. If you want to send Ajax requests, you must use the HTTP protocol.