Every time we change the code, we have to manually compile the code if we want to see the change in the browser, which is a bit of a hassle

In Webpack, configuring certain options helps you automatically compile code after it changes

1. There are problems

Let’s start by building a simple project to get a feel for the state of project development without automatic compilation

Create an empty folder, Demo, as the root directory of your project, and run the following command in this directory to install the dependencies required by your project

> # create package.json file
> npm init -y
> # installation webpack
> npm install --save-dev webpack
> npm install --save-dev webpack-cli
> # installation lodash
> npm install --save lodash
Copy the code

We then create dist and SRC directories in the root directory and create the corresponding files in the corresponding directories. The final directory structure is as follows

Demo
	- package.json
	- package-lock.json
	- webpack.config.js
	+ node_modules
	+ src
		- index.js
	+ dist
		- index.html
Copy the code

The contents of the webpack.config.js file, specifying some basic configurations for Webpack

const path = require('path');

module.exports = {
    entry: './src/index.js'.output: {
        filename: 'bundle.js'.path: path.resolve(__dirname, 'dist')}};Copy the code

Package. json file contents, add package command NPM run build

{
    "name": "Demo"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack --config webpack.config.js"
    },
    "keywords": []."author": ""."license": "ISC"."devDependencies": {
        "webpack": "^ 4.39.2"."webpack-cli": "^ 3.3.7." "
    },
    "dependencies": {
        "lodash": "^ 4.17.15"}}Copy the code

/dist/index.html file contents, importing the bundled bundle.js file

<! doctypehtml>
<html>
    <head>
        <title>Demo</title>
    </head>
    <body>
        <script src="bundle.js"></script>
    </body>
</html>
Copy the code

/ SRC /index.js file contents, create a div and use it as a child node of the body

import _ from 'lodash';

function component() {
    var element = document.createElement('div');
    element.innerHTML = _.join(['Hello'.'webpack'].' ');
    return element;
}

document.body.appendChild(component());
Copy the code

At this point, a crude Demo is built and packaged by running the build command

> npm run build
Copy the code

Open the /dist/index.html file in your browser and you should see the Hello Webpack text

Ok, now suppose we want to make a small change to the project so that the text on the screen becomes Hello World

Easy, right! All you need to do is change a bit of the/SRC /index.js file

import _ from 'lodash';

function component() {
    var element = document.createElement('div');
    // Change webpack to World
    element.innerHTML = _.join(['Hello'.'World'].' ');
    return element;
}

document.body.appendChild(component());
Copy the code

However, we need to re-run the build command NPM run build for the changes to take effect

This is very inconvenient, especially for the front-end code, sometimes really need to modify and compile dozens of times

2. Solve problems

So, is there a way to automatically compile the changed code (after saving it)? The answer is yes

There are two common ways to achieve this effect in Webpack

(1) Watch mode

The first method is to use Watch Mode, which, as the name suggests, automatically compiles code when changes are observed

You can specify this using webpack’s command line argument –watch, so that webPack will compile automatically when the code changes

> npx webpack --config webpack.config.js --watch
Copy the code

Or we can add NPM script script for future use and modify package.json file as follows

{
    "name": "Demo"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack --config webpack.config.js"."watch": "npx webpack --config webpack.config.js --watch"
    },
    "keywords": []."author": ""."license": "ISC"."devDependencies": {
        "webpack": "^ 4.39.2"."webpack-cli": "^ 3.3.7." "
    },
    "dependencies": {
        "lodash": "^ 4.17.15"}}Copy the code

All right, let’s go to watch mode

> npm run watch
Copy the code

Now modify the code, save the file, refresh the browser, and you should see the changes. The only drawback is that the browser doesn’t refresh automatically

(2) webpack – dev server. –

The second approach is to use webpack-dev-server, which provides a simple Web server that loads in real time

First, let’s install the module

> npm install --save-dev webpack-dev-server
Copy the code

Then write down the relevant configuration in the webpack.config.js file

Tell the server that the service should be set up under localhost:8080, and then make the files in the dist directory accessible

const path = require('path');

module.exports = {
    entry: './src/index.js'.output: {
        filename: 'bundle.js'.path: path.resolve(__dirname, 'dist')},// Start the development server
    devServer: {
        contentBase: './dist'}};Copy the code

Also add a NPM script script for future use, modify package.json file as follows

{
    "name": "Demo"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack --config webpack.config.js"."watch": "webpack --config webpack.config.js --watch"."start": "webpack-dev-server --open"
    },
    "keywords": []."author": ""."license": "ISC"."devDependencies": {
        "webpack": "^ 4.39.2"."webpack-cli": "^ 3.3.7." "
    },
    "dependencies": {
        "lodash": "^ 4.17.15"}}Copy the code

Ok, now open up the development server

> npm start
Copy the code

Then modify the code, save the file, and you should see the browser refresh itself and display the results