This is the second day of my participation in the More text Challenge. For more details, see more text Challenge

preface

This series of articles will cover the use of webpack5 one by one. This series is for beginners and is for those who have never used Webpack or know a thing or two about it. It is not for those who want to dive into WebPack.

start

Install webpack

Webpack depends on the Node environment. If node is not installed, install Node first.

Create a blank folder called test and enter the following command to initialize the project.

npm init
Copy the code

After you enter the command, you will be prompted to enter some information. Just enter the next step.

A package.json file is automatically created in the test folder. This file is the project description file and is used to store project information such as project name, version number, and scripts to run.

Install WebPack and webpack-CLI (if webPack4 +, install Webpack-CLI)

npm install --save-dev webpack webpack-cli
Copy the code

In the package.json file, you can see the addition of devDependencies, which contains webPack, webpack-cli, and the corresponding version number. This indicates that WebPack is installed successfully.

The basic configuration

Create a SRC directory under the root directory, create a js directory under the SRC directory, and create an index.js entry file inside the directory.

Index.js file to write the test code.

console.log('This is an entry file.')
Copy the code

Create a build directory in the root directory and create a webpack.config.js file with the following code inside.

const path = require('path')

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

Entry is used to write the entry configuration and output is used to write the exit configuration. The path.resolve method is used to generate an absolute path. It can be used to create an absolute path with the first parameter.

The purpose of this configuration is that index.js is the entry file, which is built and exported to main.js in the dist directory.

Add a build command to the script in the package.json file, as follows:

{..."scripts": {
    "build": "webpack --config ./build/webpack.config.js". },... }Copy the code

Running the NPM run build command, we can see that the root directory has an additional dist directory, which contains a main.js file.

Since there is no HTML carrier, JS will not be able to run in the browser, the next step is to add HTML.

html-webpack-plugin

Install the HTml-Webpack-Plugin, which manages HTML and can be used to develop single-page or multi-page applications.

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

Usage 1: single page

In webpack.config.js, introduce html-webpack-plugin and configure it accordingly.

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    ...
    // Add the plugins attribute
    plugins: [
        new HtmlWebpackPlugin({
          title: 'home'}})]Copy the code

Run the build command: NPM run build. As you can see, the dist directory automatically generates an index.html with the title “home page” and introduces main.js.

Usage two: multiple pages

But sometimes our page is not a page, there may be other pages. Suppose you need to develop two more pages: header.html and footer.html.

We will create an HTML directory in the SRC directory and create three files in it: index. HTML, header. HTML, and footer. HTML. Note that we need to create the index. HTML file as well. Instead, they are generated using these files as templates.

Modify the WebPack configuration as follows:

module.exports = {
  entry: path.resolve(__dirname, '.. /src/js/index.js'),
  output: {
    filename: 'main.js'.path: path.resolve(__dirname, '.. /dist')},plugins: [
    // new HtmlWebpackPlugin({
    //   title: '首页'
    // }),
    // Configure multiple htmlWebPackPlugins for as many pages as possible
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/index.html'),
      filename: 'index.html'.chunks: ['main'] // The module name corresponding to the entry file (entry configuration), which can be understood here as importing main.js
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/header.html'),
      filename: 'header.html',}).new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/footer.html'),
      filename: 'footer.html',]}})Copy the code

If we build again, we can see that there are header. HTML and footer. HTML in the dist directory. But what if header. HTML and footer. HTML have their own JS? We also need to modify the configuration of entry, Output, and HtmlWebpackPlugin.

Create header.js and footer.js in the SRC /js directory. Modify the entry in webpack.config.js.

module.exports = {
    // entry: path.resolve(__dirname, '.. /src/js/index.js'),
    entry: {
        main: path.resolve(__dirname, '.. /src/js/index.js'),
        header: path.resolve(__dirname, '.. /src/js/header.js'),
        footer: path.resolve(__dirname, '.. /src/js/footer.js'),},output: {
        // filename: 'main.js',
        filename: '[name].[fullhash].js'.// Do not specify the name of the file. Use [name] to print the original file name
        path: path.resolve(__dirname, '.. /dist')},plugins: [
    // new HtmlWebpackPlugin({
    //   title: '首页'
    // }),
    // Configure multiple htmlWebPackPlugins for as many pages as possible
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/index.html'),
      filename: 'index.html'.chunks: ['main'] // The module name corresponding to the entry file (entry configuration), which can be understood here as importing main.js
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/header.html'),
      filename: 'header.html'.chunks: ['header'] / / add chunks
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/footer.html'),
      filename: 'footer.html'.chunks: ['footer']}}),Copy the code

The dist directory contains main, header, footer, and other related jS. You may notice that the js file name has a string of codes. This string is a hash code, which is the result of “[fullhash]” in the output above. Why add this code? We all know that the browser is a cache, pack to deploy a project at a time, if the js file name or the introduction of js links have not changed, the browser will use the last cached js file, this is obviously not what we want, so every time packaging we all resource files (js, CSS, images, etc.) add a bunch of different hash code, Prevent browsers from using cached files.

clean-webpack-plugin

If you’re careful, you might notice that main.js is still there, and it would be a nuisance if we had to manually clean the dist directory every time we build.

Let’s fix this by installing the clean-webpack-plugin.

npm i -D clean-webpack-plugin
Copy the code

webpack.config.js

const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
    ...
    plugins: [...new CleanWebpackPlugin(),
    ]
}
Copy the code

You can see that each time we build, the dist directory is deleted and a new dist directory and its contents are built.

webpack-dev-server

Webpack-dev-server is a development server that implements HMR (module hot replacement). The so-called MHR means that it saves the built files in running memory, ensuring speed. Whenever your development code changes, it immediately reconstructs the files in memory, and informs the browser to update the content of the page.

With Webpack-dev-Server, we can greatly improve development efficiency.

Webpack – dev – server installation

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

webpack.config.js

module.exports = {
    ...
      devServer: {
        port: 3000.hot: true.contentBase: '.. /dist'}},Copy the code

Package. json adds the script dev

{..."scripts": {
        "dev": "webpack server --config build/webpack.config.js --open". },... }Copy the code

Run the NPM run dev command

We can see that the browser automatically opens and loads our page. If you don’t want the browser to open automatically, just delete –open from the dev script command.

Of course, you can load the page yourself by typing http://localhost:3000 (depending on the actual deployment).

Note: Some technical blogs may write this in the script command.

"scripts": {
    "dev": "webpack-dev-server --config build/webpack.config.js --open",
    ...
},
Copy the code

In webpack-cli4 (webpack-cli3), run the webpack-dev-server command. Webpack-cli /bin/config-yargs cannot be found because webpack-cli4 has removed the webpack-cli/bin/config-yargs module. If you want to use the webpack-dev-server command, you need to downgrade to webpack-cli3; otherwise, run the webpack server command instead.

At that time, when WebPack4 was just upgraded to WebPack5, I found this problem, but the WebPack document also clearly stated that webpack-dev-server was used (it was probably not changed in time), and I could not find a solution in Baidu. A solution to this problem was later found in the Github WebPack issue. So, if you find a problem, it’s a good way to check or mention the Github issue.

The complete code

directory

webpack.config.js

const path = require('path')

const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
  // entry: path.resolve(__dirname, '.. /src/js/index.js'),
  entry: {
    main: path.resolve(__dirname, '.. /src/js/index.js'),
    header: path.resolve(__dirname, '.. /src/js/header.js'),
    footer: path.resolve(__dirname, '.. /src/js/footer.js'),},output: {
    // filename: 'main.js',
    filename: '[name].[fullhash].js'.path: path.resolve(__dirname, '.. /dist')},devServer: {
    port: 3000.hot: true.contentBase: '.. /dist'
  },
  plugins: [
    // new HtmlWebpackPlugin({
    //   title: '首页'
    // }),
    // Configure multiple htmlWebPackPlugins for as many pages as possible
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/index.html'),
      filename: 'index.html'.chunks: ['main'] // The module name corresponding to the entry file (entry configuration), which can be understood here as importing main.js
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/header.html'),
      filename: 'header.html'.chunks: ['header']}),new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/footer.html'),
      filename: 'footer.html'.chunks: ['footer']}),new CleanWebpackPlugin(),
  ]
}
Copy the code

package.json

{" name ":" test ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" dev ": "webpack server --config build/webpack.config.js --open", "build": "webpack --config ./build/webpack.config.js", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": {"clean-webpack-plugin": "^4.0.0-alpha.0", "HTML -webpack-plugin": "^ 5.3.1 webpack", ""," ^ 5.38.1 ", "webpack - cli" : "^ 4.7.0", "webpack - dev - server" : "^ 3.11.2",}}Copy the code

series

Using WebPack5 (0) : Concepts Using WebPack5 (1) : Starting Using WebPack5 (2) : Configuring Multiple environments Using WebPack5 (3) : Loading the CSS Using WebPack5 (4) : Load resource file Webpack5 use (5) : Babel translation JS code use (6) : optimization