This is the third day of my participation in the August Text Challenge.More challenges in August

In the previous

React – Build projects from scratch – WebPack configuration

preface

The react component uses import and JSX syntax and has been successfully packaged. In this article we will address the following issues:

Why can projects created with create-react-app be accessed with localhost:3000? And the project is automatically updated (hot update) every time the code is changed?

It’s probably because of this:

Hot updates are implemented mainly because of webpack-dev-server, which opens a Web service that listens for file changes and triggers webpack compilation, which does not generate static files directly but instead stores them in memory. The exact mechanism remains to be explored.

Since it’s a Web service, we can access it with an IP address and port number, so we can separate the front and back configurations (no need to run a project server locally), and we can configure proxies to debug the interface, so we can write a simple Node service to mock data. You can also use proxies to solve cross-domain problems in development (which will not be covered in this article but will be explored later), so Webpack-dev-server provides a great convenience for front-end development.

Take a look at webpack-dev-server, a classic runtime schematic, for those of you who are interested in taking a look at it (I’m interested, but I don’t have time, so I’ll check it out later)

I don’t want to work hard anymore

Webpack dev – server configuration

The webpack-dev-server configuration can be configured as webpack-dev-server.

NPM I webpack-dev-server -d = NPM I webpack-dev-server -d = NPM I webpack-dev-server -d

Then configure webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  .....
  / / webpack - dev - server configuration
  devServer: {
    compress: true./ / start Gzip
    port: 3000./ / port
    open: true // Automatically open the browser}}Copy the code

There are quite a few configuration items for devServer, but this time we have three.

After executing NPX webpack-dev-server, you can see that the browser automatically opens localhost:3000 and displays our React component. After modifying the component code, we implemented a hot update.

NPX is used because webpack-dev-server is not installed globally and therefore cannot be run directly

For easy startup, we can configure the start command in the package.json file

"scripts": {
  "start": "npx webpack-dev-server"
}  
Copy the code

To start the project, simply execute NPM start.

The next article

React – Build projects from scratch – configure various Webpackers