This article has been published on my official account. For more original technical articles, please pay attention to my official account “Byte Reverse Journey”.

Today brings the second part of webpack introduction series. If you are not familiar with Webpack, you can read the first one hour Introduction to Webpack. This article focuses on plug-in usage and hot update packaging, will involve three knowledge points, are relatively basic and important content. Including: plug-in usage (HtmlWebpackPlugin), file listening, hot update packaging. The code for the tutorial has been uploaded to Github. If you need it, you can download it. It is best to follow the steps themselves, the code is for reference only.

If any knowledge points or part of the document used in this article feel strange, strongly suggest you turn to one hour introductory Webpack to preheat learning, I believe you read the first article, will be more appetite to eat today’s dish. Of course, if you have already started webpack, this article is just a summary of your knowledge points, the same collectible value.

HtmlWebpackPlugin plugin usage

Let’s start with the concept of plug-ins. Webpack has a rich Plugin interface. Most of the functionality of WebPack itself uses this plug-in interface. This plug-in interface makes WebPack extremely flexible. To sum up, plug-ins can be used for package file optimization, resource management, and environment variable injection.

To put it bluntly, a plug-in means THAT I don’t have the capability, but I can open up some plug-in interface, and then you can develop some plug-ins that you want, and then plug them into Webpack to do what you want. Browser plug-ins are the same thing. You can also develop your own plug-in if you wish.

Now to look at the HtmlWebpackPlugin plugin, we are manually created in front of the HTML page, and this plug-in can automatically generate the basic HTML page, relatively simple to use. Here are the steps:

Installing a plug-in

npm install --save-dev html-webpack-plugin
Copy the code

Once installed, it can be configured and used later.

Configured to use

As shown below, add an HtmlWebpackPlugin constant to the webpack.config.js file, reference the plug-in, and then add the plugins node to the configuration below, which contains the plug-in instance. Plugins stand for plug-in entry, where all plug-ins are configured.

const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        index: './src/index.js',},output: {
        path: path.join(__dirname,'dist'),
        filename: 'index.js'
    },
    mode: 'production'.plugins: [new HtmlWebpackPlugin()],
    module: {
        rules: [..]
    }
}
Copy the code

Shielding rely on

Once configured, run NPM run build to see what happens. The result is a glowing piece of code, as shown below:

I’ve just taken part of it, and there’s a lot more down here, but just look at the top one, and it’s like this:

ERROR in   Error: Child compilation failed:
  Module build failed (from ./node_modules/babel-loader/lib/index.js):

  SyntaxError: E:\demo\newwebpack\section two\node_modules\
  html-webpack-plugin\default_index.ejs: Unexpected token (1:0)
Copy the code

The babel-loader is used in the first part of this tutorial to parse es6 syntax. The babel-loader is used in the first part of this tutorial to parse es6 syntax. The solution to this problem is to allow the project to ignore dependencies when it is built as follows: exclude: /node_modules/ babel-loader

{ test: /.js$/ , use: “babel-loader”, exclude: /node_modules/ }

Ok, fix the problem, run NPM run build again, and you’ll see an index.html file generated in the dist directory.

In fact, the plugin has related configuration, we can try to experience:

new HtmlWebpackPlugin({
        title: 'leaningwebpack'.filename: 'webpack-index.html'.favicon: 'webpack.ico'
    })
Copy the code

Title: Sets the title of the generated HTML file; Filename: indicates the name of the HTML file. The default value is index.html. Favicon: Sets a web page icon

The HTML -webpack-plugin plugin can be found in this article

Since there is no content in the generated HTML file, some of the styles we used in lecture 1 are missing. You can modify the code in helloWebpack.js:

export function hellowebpack() {
    return '<div class="color-text">hellowebpack</div>'
}
Copy the code

Two, file monitoring

File monitoring is the automatic reconstruction of a new output file when changes are detected in the source code. This is helpful for our development, because instead of having to run a package every time we change something, it’s a waste of time.

There are two ways to implement file listening:

1, “watch” : “webpack – watch”

2. Set watch: true in webpack.config.js

The first listening mode:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack"."watch": "webpack --watch"
  },
Copy the code

Add a “Webpack –watch” configuration (alias watch) to the package.json file instead of Webpack, then run NPM Run Watch at build time and you can see that the watch has started.

Then we make some changes in the helloWebpack.js file and see that Watch is also tracking execution. Refresh the browser and see the changes.

export function hellowebpack() {
    return '<div class="color-text">hellowebpack123</div>'
}
Copy the code

The second listening mode:

Add the watch:true line to the configuration root of the webpack.config.js file.

Then run NPM run build to also start listening.

This is essentially the same as above, and requires a browser refresh to see what happens when we modify the project file. In fact, it is polling to determine whether the last edit time of a file has changed. When a file has changed, it will not tell the listener immediately, but cache it first and wait for the aggregateTimeout time to run. The watch configuration in the listening state is listed below for your reference.

module.export = {
// By default, false is disabled
watch:true.// Watch starts with watchOptions
watchOptions: {
// The default value is empty. Sets files or folders not to be listened to. Supports regular matching
ignored: /node_modules/.// Wait 300ms for change to occur. Default 300ms
 aggregateTimeout:300.// Set the polling file change time, the default is 1000 times per second
 poll:1000}}Copy the code

So the question is, is it possible to update the browser without manually refreshing it? There’s a way. Hot update is here.

Hot update

Hot updates mean that you can change your code in the editor and see the same updates in the browser. Sounds amazing, right? Here are the steps:

WDS does not refresh the browser

WDS is short for Webpack-dev-server. Compared to the file listening method mentioned above, this solution does not output files itself, but puts them in memory, which has better performance. This scheme USES HotModuleReplacementPlugin this plug-in, belong to webpack plug-ins. Here are the steps:

The installation

npm i webpack-dev-server -D
Copy the code

Install the webpack-dev-server dependencies that will be used later, and then add the configuration to use them.

Configured to use

Add configuration in package.json

"Dev" :"webpack-dev-server --open"
Copy the code

Then add the configuration to webpack.config.js, declaring a constant webpack first

const webpack = require('webpack');
Copy the code

Add a plugin to the array under the plugins node

new webpack.HotModuleReplacementPlugin()
Copy the code

Finally, add a devServer configuration at the same level as plugins, where contentBase indicates that the hot update package is for the content in the dist file, and hot:true indicates that the hot update state is enabled.

devServer: {
     contentBase: './dist'.hot: true
    },
Copy the code

Overall, the webpack.config.js configuration looks like this:

Once configured, let’s test the effect by running NPM run dev

You’ll see that it runs webpack-dev-server –open, and if you see a page like this, you’re opening a list of files in the dist directory.

Select your HTML page and let’s test the hot update effect. Modify the content in helloWebpack.js,

export function hellowebpack() {
    return '<div class="color-text">hellowebpack12345</div>'
}
Copy the code

Save the document, then immediately look at your browser and see that the page automatically refreshes to show the latest content, and the hot update effect has been achieved.

Ok, that’s all for today. The code is on Github. Look at this section and start following the article based on Section one, section two is the final code state.

Code address: github.com/bridgeToVil…

This article is published in my public number byte reverse brigade, if interested in big front-end technology, welcome to pay attention to my public number