Writing is not easy, without the permission of the author is prohibited in any form of reprint! <br/ thumb up > <br/ thumb up > <br/ thumb up > <br/ thumb up >


Link to the original Nuggets

Webpack-Dev-Server

Why build a local server

  • The code developed so far requires two operations in order to run

    • npm run buildcompile
    • Open the HTML file through the live-server or directly through the browser to see the results
  • Webpack provides several alternative ways to automate compilation

    • Webpack watch mode
    • Webpack-dev-server
    • Webpack-dev-middleware

Webpack Watch Mode

  • Webpack provides watch mode

    • In this mode, Webpack depends on all the files in the diagram, and as soon as one of them is updated, the code is recompiled.
    • No need to do it manuallynpm run build
  • How to turn it on?

    • Approach 1: Add watch:true to the exported configuration
module.exports = {
    entry: "./src/index.js",
    output: {
        filename: "js/bundle.js",
        path: path.resolve(__dirname, "build"),
    },
    watch:true,
}
  • Method two: in the command to start WebApck, add the –watch flag
npm script:{
 "watch": "webpack --watch"
}
# npm run watch

Webpack Dev Server

  • The above method can listen for changes in the file, but does not automatically refresh the browser function

    • Webpack-dev-server can be implemented
  • The installation

    • npm install --save webpack-dev-server
  • Modify NPM script while configuring devServer under the devServer property in the configuration file
script:{
    "serve":"webpack serve"
}
  • Webpack-dev-server is not written to any output file after compilation. Instead, the bundle file is kept in memory

    • In fact, webck-dev-server uses a library called memfs.

Webpack Dev Middleware

  • Webpack-dev-middleware is a wrapper that sends Webpack-processed files to a server

    • Webpack-dev-server uses it internally, however it can also be used as a separate package for more custom configuration on demand
    • Use it with a server, such as Express.
    • npm install --save express webpack-dev-middleware
  • Write Server. Js
const express = require("express") const webpack = require("webpack") const webpackDevMiddleware = require("webpack-dev-middleware") const app = express() const config = require("./webpack.config") const compiler = webpack(config) app.use(webpackDevMiddleware(compiler,{ publicPath:config.output.publicPath }),()=>{ Console. log(" here is a callback function ")}) app.listen(3000,()=>{console.log("Server running")})
  • Node Server.js runs a service and listens for file changes and refreshes the browser.

PublicPath

  • There are two important properties in Output: path and publicPath

    • PATH: Used to specify the output path of the file, which is a heap path
    • PublicPath: The default is an empty string that specifies a publicPath for the resources in our project
  • So this publicPath, which is a little bit hard to understand, is just giving us a bundle of resources, giving it a path

    • Resource path = output.publicePath + the path to package the resource (e.g. “js/[name].bundle.js”)
  • The value of the commonly used

    • ./ : This relative path can be used in the local environment
    • / : The server is deployed to + /js/[name].bundle.js
  • The publicPath of DevServer, Output and WebPackDevMiddleware should be the same

ContentBase

  • ContentBase in devServer doesn’t have much use for accessing the packaged resource directly, but it does have a role in specifying where to look for the content if the packaged resource depends on other resources:

    • For example, in index.html, we need to rely on a file called abc.js, which we store in a public file.
    • How should we import this file in index.html?

      • ;
      • This way, the browser can’t find the folder through a relative path;
      • ;
      • How do I tell it to find out the existence of this file? Set ContentBase;
  • There is, of course, one more property in devServer that listens for ContentBase to be recompiled if it changes: watchContentBase.

The Proxy agent

Proxy is a configuration option commonly used in our development to set up proxies to solve cross-domain access problems

  • Set up the

    • Target: identify the agent to the destination address, for example, / API/moment will be acting to http://localhost:8888/api/moment
    • Pathrewrite: By default, our/APIs are also written to URLs and can be used if you want to delete them
    • Secure: By default, servers that forward to HTTPS are not accepted, set to false if desired
    • ChangeOrigin: Indicates whether the host address in the request headers after the agent is updated
    • HistoryApiFallback: Resolved SPA page refresh and return 404 after routing jump

      • Boolean value: Default is false, if set to true, the contents of index.html will be returned automatically on refresh when 404 error is returned
      • Object value: You can configure the rewrites property

        • You can configure from to match paths and determine which page you want to jump to. See the official documentation for details.

Other Config

  • hotOnly

    • By default the page will refresh when the code fails to compile. You do not want to refresh the hotOnly:true setting
  • Host address

    • The default value is localhost
    • Set 0.0.0.0 if other PCs can also access it
  • The difference between localhost and 0.0.0.0

    • Localhost is essentially a domain name that will resolve to 127.0.0.1
    • 127.0.0.1 is an address-swappable packet that means the host sends it and accepts it directly

      • Normal database package often applied layer -> transmission layer -> network layer -> data link layer -> physical layer
      • The return address, on the other hand, is obtained directly at the network contact layer
      • When listening on 127.0.0.1, the host under the same network segment cannot be accessed by IP address.
    • 0.0.0.0: Listen for all addresses on IPv4 and find different applications based on the port.

      • When listening on 0.0.0.0, hosts under the same network segment can be accessed by IP address.
  • Port

    • Set the listening port. Default is 8080
  • Open whether to open a browser

    • Default is false, which opens the browser
    • You can also set similar Google Chrome equivalents
  • Compress turns on GZIP COMPRESSION for static files

    • Default is false and can be set to true

Configuration of the sample

devServer: {
    hot: true,
    hostOnly:true,
    host:"0.0.0.0",
    port:8080,
    open:true,
    compress:true,
    proxy:{
        "/api":{
            target:"http://localhost:8888",
            pathRewrite:{
                "^/api":""
            },
            secure:false,
            changeOrigin:true
        }

    }
}

Hot Module Replacement

  • What is the HMR?

    • The full name of HMR is Hot Module Replacement, which translates as Hot Replacement of modules
    • Hot module replacement refers to the process of replacing, adding, and removing modules while the application is running without having to refresh the entire page.
  • HMR can speed up development in several ways.

    • Not reloading the entire page, so that some application state is not lost;
    • Just update what needs to change, saving development time
    • If you change the CSS and JS source code, it will be updated immediately in the browser, which is equivalent to changing the style directly in the browser’s DevTools.
  • How to use HMR?

    • By default, webpack-dev-server already supports HMR; you just need to turn it on.
    • When you modify the source code, the entire page will refresh automatically, using live reloading, without HMR on.
  • How to open

    • Modify the webpack. Config. Js
module.exports = {
    entry: "./src/index.js",
    output: {
        filename: "js/bundle.js",
        path: path.resolve(__dirname, "build"),
    },
    watch:true,
    mode: "development",
    devServer:{
      hot:true
    },
 }
  • Refresh the entire browser after the update, because you need to define the modules that use the HMR.
If (module. Hot) {module. Hot. Accept (". / App. Vue ", () = > {the console. The log (" vue updated ")})}

Framework of HMR

One question: when developing other projects, do we often need to manually write module.hot.accpet related APIs?

  • For example, in the development of Vue and React projects, we modify the component and want to make hot update. What should we do at this time?
  • The community already has well-established solutions for these:

    • For example, in VUE development, we use VUE-Loader, which supports the HMR of VUE components and provides an out-of-the-box experience.
    • For example, in React development, there is React Hot Loader, which can adjust React components in real time (React has been officially deactivated, instead of using React Refresh).

The Vue HMR

  • The loading of a VUE requires a VUE-loader, and the VUE-loader loads HMR processing by default
  • Install the dependencies required to load VUE

    • npm install vue-loader vue-template-compiler
  • Configuration Webpack. Config. Js
const VueLoaderPlugin = require("vue-loader/lib/plugin")

module: {
    rules: [
        {
            test: /\.vue$/,
            use: ["vue-loader"]
        },
   ]
},
plugins:[new VueLoaderPlugin()]

The React of HMR

  • Previously, React implemented HMR with React Hot Loader, but now React – Refesh is used
  • Installation dependent dependencies

    • npm install @pmmmwh/react-refresh-webpack-plugin react-refresh
  • webpack.config.js
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin")

plugins: [
    new ReactRefreshWebpackPlugin(),
],
  • babel.config.js
module.exports = { presets: [ ["@babel/preset-env", { useBuiltIns: "usage", corejs: 3.8}], [" @ Babel/preset - react "], [" @ Babel/preset - typescript "]], the plugins: [[' react - refresh/Babel ']]}

The principle of HMR

  • So how does HMR work? How can I update the contents of only one module?

    • Webpack-dev-server creates two services: a service that provides static resources (Express) and a Socket (Net.Socket).
    • Express Server is responsible for serving static resources directly (packaged resources are requested and parsed directly by the browser)
  • HMR Socket Server is a Socket long connection

    • One of the best benefits of a long connection is that after the connection is established, both parties can communicate (the server can send files directly to the client).
    • When changes to the corresponding module are heard during the service, two files.json (manifest file) and.js (update chunk) are generated.
    • These two files can be sent directly to the client via a long connection.
    • After the browser gets the two new files, it loads them through the HMR Runtime mechanism and updates them for the modified modules.
  • Link to the original Nuggets
  • Nuggets: Front end LeBron
  • Zhihu: Front-end Leon
  • Continue to share technical blog posts, follow the WeChat official account 👇