This is the seventh day of my participation in the First Challenge 2022. For details: First Challenge 2022.

From the previous articles, we’ve learned how to package and present projects using WebPack so far, but have you noticed that each update requires a back-and-forth between the following steps:

  1. Write the code
  2. packaging
  3. run
  4. Browser View effect

Obviously, this kind of development mode is too primitive, and the efficiency is extremely low. Today, we respectively change this working mode through the Watch monitoring mode of Webpack and the configuration of devServer development server, so as to improve our development efficiency.

I. Watch monitoring mode of Webpack

The easiest way to do this is to add the –watch (-w) parameter to the webpack command:

    npx webpack --watch
Copy the code

After startup, the command line cursor flashes, indicating that WebPack is in listening mode. At this time, you just need to open the HTML page by hand to see the effect. When the files in the project are modified, WebPack will automatically repackage and output, of course, we need to manually refresh the browser to see the latest effect.

At this point we thought, can we make WebPack smarter and more efficient? It would be nice if Webpack repackaged to refresh the browser automatically for us

In fact, Webpack has already helped us to think of this effect, which is to use the development server devServer configuration of WebPack

DevServer development server

DevServer allows you to create a server in your local development environment. This server is based on Express. It enables you to automatically refresh the browser when code changes in your project, in addition to packaging and compiling.

Installation and Configuration

To use the devServer configuration, the webpack-dev-server module must be installed

    npm install webpack-dev-server
Copy the code

After installation, you only need to set the devSever property in the webpack.config.js configuration file, which is set to an empty object because devServer can start with zero configuration

    module.exports = {
        // ...
        devServer: {}}Copy the code

Start the server with zero configuration

You don’t need to set any parameters to start devServer (using the default configuration). You can start a server with default port 8080 by simply using the following command in the command output

    Start directly from webpack-dev-server
    npx webpack-dev-server

    # Start via webpack CLI (recommended)
    npx webpack server
Copy the code

If you do not want to use the NPX command, you can also use the NPM script command to start the server. You need to set the scripts property in the package.json file, and then run the NPM run dev command to start the server.

    //package.json
    {
        / /...
        "scripts": {"dev":"webpack server"}}Copy the code

After the server is started, devServer will listen for changes in the project files, automatically repackage and compile the files when there are changes, and update the page effect with HMR hot replacement or automatic browser refresh. However, unlike Watch mode, webPack does not generate specific files on disk, but in memory to make it more efficient, so we don’t see the effect of the packaged files in the actual directory.

With the devServer development server, we can experience the development style of modifying code while viewing the results of the changes in real time

Configuration parameters

Although you can use the default configuration of devServer to start the server, but to take full advantage of the powerful functions of devServer, you still need to understand every parameter of devServer. The configuration of this module is many, you can check the website of WebPack for yourself. Here are some common configuration options:

  • Static: Specifies the static resource directory (default is the public folder). It is used to store static resource files that are not webpack packed. Favicon.ico), which can be a single String directory or an Array of directories (older versions of 4.x use contentBase).

        module.exports = {
            / /...
            devServer: {// 4. X version
                contentBase:path.resolve('./public'),
    
                // 5. X version
                static:path.resolve('./public')}}Copy the code
  • Port: Specifies the server port (default: 8080).

    If port 8080 is used, it will be automatically incremented to 8081, and so on

  • Hot: enable hot module replacement (default: true)

    Open module hot replacement, when listening to the project file is modified, devServer is without refreshing the whole page by using a new module to replace the old module to achieve real-time preview, it particularly useful to keep the form input state, such as disable this feature, by automatically refresh the entire page to achieve real-time preview, The contents of the input form will naturally be cleared

  • Open: whether to open the browser automatically (default: false)

    Lazy mode, automatically opens browser when devServer is started

  • HistoryApiFallback: Whether the history route is supported (default: false)

    When this property is enabled, the server automatically responds to the contents of the front page when the page visited (404) does not exist, which is especially useful when using the history route in a single page application (SPA)

  • host

    By default, only the local machine can access the devServer. Set host to 0.0.0.0 to make it accessible to other devices on the LAN

  • Compress: Enables gzip server compression

    Setting this parameter can improve the page access speed

  • Proxy: Server proxy (typically used to solve Ajax cross-domain problems)

    Proxy server based on HTTP-proxy-Middleware

    There are often scenarios where the back-end interface works on the http://10.3.131.2:3000 server and its own webpack startup server is http://localhost:8080, where cross-domain restrictions occur when ajax requests are made in code, If the backend interface is not open for CORS cross-domain resource sharing, it is not directly accessible by default. In this case, proxy is very useful.

        module.exports = {
        / /...
        devServer: {
            proxy: {
                '/api': 'http://10.3.131.2:3000',}}};Copy the code

    When an Ajax request address begins with/API, it goes to the proxy server, as in: The following request address is http://localhost:8080/api/users, but because the address is/API begins, so within devServer server will automatically request on http://10.3.131.2:3000

        const xhr = new XMLHttpRequest()
        xhr.open('get'.'http://localhost:8080/api/users'.true)
        xhr.send()
    Copy the code

    Proxies can also be written in various ways to meet different requirements, such as when the target interface address does not have/API:

    • Requested address:http://localhost:8080/api/users
    • Interface address:http://10.3.131.2:3000/users

    In this case/API is only used to match the proxy rule, but the real interface address does not have/API, so pathRewrite is used to rewrite the path (remove redundant characters).

    In addition, by default the agent will retain the Origin of the host header (the Origin field in the request header is http://localhost:8080). Some interface servers may restrict the Origin character. We can override this behavior by setting changeOrigin to true. The Origin field is overwritten as http://10.3.131.2:3000

        module.exports = {
            / /...
            devServer: {
                proxy: {
                    '/api': {
                        target: 'http://10.3.131.2:3000'.pathRewrite: { '^/api': ' ' },
                        changeOrigin:true}},}};Copy the code

The articles

  • Webpack 5 Tutorial 1: Getting to know Webpack
  • Webpack5 tutorial 2: resource modules and loaders
  • Webpack5 tutorial 3: plugins