As described in the previous article, once entry, Output, and Loader are configured, basic code packaging is complete. In addition, WebPack also provides a lot of plug-ins, can simplify some tedious operations, such as automatic cleaning of the package generated directory.

  • Plug-in address:
    • www.webpackjs.com/plugins/
    • Github.com/webpack-con…

In addition, it also provides a variety of development tools such as sourceMap and devServer.

Plugin

Loaders are used to convert certain types of modules, while plug-ins can be used to perform a wider range of tasks. Plug-ins range from packaging optimization and compression to redefining variables in the environment. Plug-in interfaces are extremely powerful and can be used to handle a wide variety of tasks.

The following examples show how plug-ins are used, and more plug-in apis are available through the above connection.

CleanWebpackPlugin

The clean-webpack-plugin automatically cleans (removes) the previously residual build directory each time you pack.

  • The installation
npm install --save -dev clean-webpack-plugin
Copy the code
  • Configuration and Use
//webpack.config.js
const {CleanWebpackPlugin} = require('clean-webpack-plugin');

module.exports = { ... .plugin: [newCleanWebpackPlugin(); ] . }Copy the code

HtmlWebpackPlugin

After wepack is finished, an HTML file is automatically generated and the packed JS file is imported into the HTML.

  • The installation
npm install --save-dev html-webpack-plugin
Copy the code
  • Configuration and Use
//webpack.config.js

const HtmlWebpackPlugin = require('html-webpack.plugin');

module.exports = { ... .plugin: {... .new HtmlWebpackplugin({
      title:'app'.filename:'app.html'.template:'./src/html/index.html'}),... },... }Copy the code
  • template./scr/html/index.htmlcontent
<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title><%=htmlWebpackPlugin.options.title%></title> 
</head>

<body>
    <h1>html-webpack-plugin</h1>
</body>

</html>
Copy the code

MiniCssExtractPlugin

Automatically extracts csS-related configurations and exports them to a separate. CSS file.

  • The installation
npm install --save-dev mini-css-extract-plugin
Copy the code
  • Configuration and Use
const MiniCssExtactPlugin = require('mini-css-extract-plugin');

module.exports = { ... .plugin: {... .new MiniCssExtactPlugin({
  		filename:'./css/app.css'}),... },... }Copy the code

SourceMap

In actual use, the code that is compiled and packaged by WebPack is usually run on the browser. If the code reports an error, it is often troublesome to debug and time-consuming to locate the cause of the problem. SourceMap gives us a mapping (compiled code => compiled code) for easy debugging.

We can start sourceMap with the devtool option in webpack.config.js.

//webpack.config.js
module.exports = {
  mode: 'production'.devtool: 'source-map'. }Copy the code
  • After compiling, sourceMap generates a corresponding.map file for each compiled file and adds a comment to the compiled file to tell the browser that the compiled file has a mapping table.

  • Most modern browsers like Chrome recognize.map files, and you can see the mapping provided by sourceMap under the Source option in the browser debug console, which greatly improves our coding efficiency.

WebpackDevServer

Every code change requires recompiling, packaging, and refreshing the browser, which is particularly troublesome and can be improved by installing webpackDevServer. The functionality is similar to that provided by vscode: Live Server. Every time we update the code, DevServer automatically compiles the packaged code and refreshes the browser (global refresh by default).

  • The installation
npm install --save-dev webpack-dev-server
Copy the code
  • To enable the

    • Enable with NPX at the command line
    npx webpack-dev-server
    Copy the code
    • Add the following fields to the package.json script and use them on the command linenpm run buildTo enable the
    . ."scripts": {
      "build": "webpack-dev-server" // Can automatically find the corresponding webpack-dev-server file in the./node_moudle/. Bin/directory
    }
    Copy the code
  • configuration

//webpack.config.js

module.exports = { ... .devServer: {
  	// Path of the generated virtual directory
  	contentBase: "./dist".// Automatically start the browser
  	open: true.// devServer port (default 8080)
  	port: 8888}}Copy the code

The following are common configuration options for devServer: proxy and local hot updates. See the official website for more configuration apis.

Proxy

It is mainly used to solve cross-domain request problems. The principle is back-end proxy.

Cross-domain: a security policy that exists in the browser; There are no cross-domain issues on the back-end server.

During daily development, for example, devServer is configured to listen on port 8888 and a back-end specific service API is running on port 8081. Then we have cross-domain problems when we need to request the API on some business logic. This is handled through the DevServer.proxy configuration.

  • configuration
//webpack.config.js

module.exports = { ... .devServer: {
  	// Path of the generated virtual directory
  	contentBase: "./dist".// Automatically start the browser
  	open: true./ / devServer port
  	port: 8888.proxy: {
      '/api': {
      	target: 'http://localhost:8081' //8081 points to the server port on which the API is running}}}}Copy the code

Note that the front end code is still running under the environment of devServer, namely http://localhost:8888, when he call/API to send back the request is http://localhost:8888/api, DevServer receives the request and then forwarded to port 8081, devServer actually sent request is http://localhost:8081/api

Hot Module Replacement

DevServer supports automatic page refresh, using the Live Loader, but this automatically refreshes the entire page every time the code changes, and refreshing the entire page in practice often brings some inconvenient factors: For example, when a page contains a form or an input field, the refresh will throw out the data that has been filled in. To solve this problem, devServer provides us with a way to refresh the entire moon surface locally instead of the entire moon surface.

The HMR-Hot Module replacement function replaces, adds, or removes modules while the application is running without reloading the entire page. Significantly speed up development in the following ways:

  1. Preserve application state that is lost during a full page reload.
  2. Update only the changes to save valuable development time.
  3. When CSS/JS changes are made in the source code, they are immediately updated in the browser, which is almost equivalent to changing styles directly in the browser DevTools.

From official documents

  • configuration
//webpack.config.js

module.exports = { ... .devServer: {
  	contentBase: "./dist".open: true.port: 8888.// Enable hot update
  	hot:true.// Even if HMR does not work, do not refresh the entire page (select enable)
    hotOnly:true,}}}Copy the code
  • use

    • When HMR is enabled, a module.hot property is exposed. At this point, when the code changes, devServer immediately compiles and notifies the browser for a partial refresh. So we need to listen for events and perform immediate local refreshes when we need to make changes to the module.
    //fn1.js
    
    export default function() {
        console.log('Fn1 module executed -1');
    }
    Copy the code
    //index.js
    
    import fn1 from './fn1.js';
    box1.onclick = fn1;
    
    if (module.hot) {// If HMR is enabled
        module.hot.accept('./fn1.js'.function() {
          The accept method accepts and triggers a callback function in response to the update when the listening event changesbox1.onclick = fn1; })}Copy the code

The above is some preliminary understanding and exploration of Webpack learning, the content of the article mainly comes from:

1. Course content: www.kaikeba.com/

2. Webpack official document: webpack.js.org/concepts/

3. Your own understanding