Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

preface

Today we will take a look at webPack basics and configure a project from 0 to 1 that can parse JS and CSS and add hot updates. Article code entry webpack01 (welcome everyone star🌟). My style of writing is always to understand why there is such a thing, and if we can only apply it without understanding why it exists and how it works, then in the long run we will be called tool people. So I’ll have a big article about why, and I hope you can absorb the essence of it.


Why Webpack

Because webPack configuration items are complex, many concepts, confusing, difficult to remember, loader and plugin many reasons, so we are afraid to learn something else easy to grasp. Therefore, based on the above reasons, we have not really mastered Webpack, so we start webpack series today, is to let every student can really mastered Webpack, for your use


What can we learn from this passage

  • Why webpack?
  • What webPack can do
  • What does the Webpack workflow look like
  • Configure a project from 0 to 1 that can parse JS, CSS, and enable hot updates

Webpack view

First of all, let’s talk about the concept of Webpack. We will explain it in terms of why, What and how


Why webpack?

Before we talk about why we need WebPack, let’s look at what engineering is.

In fact, engineering is automation, is to use a series of processes to achieve code, improve efficiency.

As the amount of code on the client side increases and the number of users increases, the large amount of code means that we need to properly organize the code, improve page loading performance, improve interaction, improve automated deployment, and let programmers spend more time on business code.


What webPack can do

  • Code transformation

Convert unsupported languages such as typescript, coffeescript, react, es7, 8,9,10, less, etc., into browser-supported HTML, js, and CSS

  • File optimization

Compress JS, HTML, CSS, merge compressed images

  • The code segment

This is undoubtedly the most important

We need a more flexible delivery method, and in most cases, finding a balance in the middle of extremes is best. For example, when compiling all modules, you can divide them into many smaller modules. In this way, we can split the request into many smaller requests, and the segmented module will be requested only when needed. So the initial request does not contain all of the code, reducing the transfer pressure. It is up to the programmer to decide how to split the code.

This idea comes from Google’s GWT. More information in Code Splitting.

  • Hot update

Listen for changes in source code, automatically rebuild, and refresh only the changed parts

  • Package the corresponding code according to the environment

Development environment we focus on debugging, production environment we pay more attention to experience, small size

  • Code check

Code compliance is verified and unit tests pass before it is submitted to the repository


What is Webpack?

Webpack is a static module bundler for modern JavaScript applications.


The working process

Webpack will recursively search for modules in Entry and find corresponding conversion rules according to Loader every time it finds a module. After converting the current Module, parse the modules that the current Module depends on.

Modules are grouped by Entry. An Entry and its dependent modules are assigned to the same Chunk, and Webpack outputs these chunks. Webpack executes the Plugins logic at appropriate times throughout the process.


Some basic concepts

  • Mode: indicates the mode. There should be development mode, production mode, etc

  • The first step in webPack construction begins with an entry, which can be abstracted as input

  • Output: To export the desired code and output the result after the Webpack has gone through a series of processes.

  • Loader: module converter, used to convert the original content of a module into new content as required. Webpack cannot process.jpg,.txt and other contents, so file-loader and URL-loader are required to assist in processing.

  • Plugins: Extensions that inject extension logic at specific points in the Webpack build process to change build results or do whatever else you want to do.


The build process

Create a package.json file

Let’s start by creating a directory called WebPack01, which is kind of arbitrary

Then we need to create a package.json file

What is the package.json file for?

Each project requires a package.json file, which records the configuration information of the project, such as our project name, package entry file, project version, etc., as well as the various dependencies required, and the important script field, which specifies the NPM command line abbreviation for the script command to run.

On the command line, enter the following command to generate package.json

npm init -y
Copy the code

A package.json file is generated under the directory

Install the Babel and Webpack dependencies and configure webpack.config.js

Install the requisite Babel and WebPack dependencies

Babel-loader // Babel webpack webpack-cli // Webpack can be run using the command Webpack-dev-server // Can start localhost serviceCopy the code

Note: Use version 4 of WebPack as much as possible, so that you can avoid a lot of hair-dropping errors when you become more dependent

Next we create the SRC directory to create the app.js file

const name = "welcome to webpack";
export default {
  name,
};

Copy the code

Create the index.js file, which is the entry file

import App from "./App.js";
console.log(App.name);
Copy the code

Why are we doing this, just to see if import works, because import is es6 syntax

Now the directory structure looks like this

What we’re going to do now is simply print the console.log value and print ws as a test.

Next, configure webpack.config.js

const path = require("path"); Module.exports = {mode: "development", // this is an entry: path.join(__dirname, "./ SRC /index.js"), // this is an entry file output: {filename: "bundle.js", // the filename to print path: path.join(__dirname, "./dist"), // the output file directory}, module: {rules: [{test: /\.js$/, exclude: /node_modules/, // exclude: /node_modules/ "Babel-loader ", // use babel-loader to parse js files and output syntax that can be recognized by browsers},],},};Copy the code

You also need to configure the start command in the package.json script, as shown below

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

After doing all that, we type on the command line

npm start
Copy the code

Dist directory, dist directory, bundle.js, so if we want to see the print results in the browser console and we need HTML files, we let webpack generate automatically, and then we need to use htML-webpack-plugin. The advantage of using a plug-in is that it automatically references the packaged JS file

Automatically generate HTML using the HTML-webpack-plugin

So now we are creating a public directory and create index.html as follows

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, Initial scale = 1.0 "/ > < title > webpack based article < / title > < / head > < body > < div id =" root "> < / div > < / body > < / HTML >Copy the code

Note: write a div tag with the id root so that the content can be displayed in HTML later, and configure the html-webpack-plugin in webpack. See how memorable the name is

const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { ... , plugins: [ new HtmlWebpackPlugin({ template: "./public/index.html", }), ], };Copy the code

We have the configuration file configured, so now we need to print our results on the console on the browser to see if WS is printed.


Configure devServer to automatically open the browser and refresh the page when you modify the content

Now look at the packing result

We have generated the js and bundle files we want, but we need to manually open index.html, which is designed to do automatically, so we can configure devServer in webpack.config.js

const path = require("path"); . module.exports = { ... , devServer: { static: path.join(__dirname, "./dist"), open: true, hot: true, }, };Copy the code

For now, we only need to configure it like this. There is one more thing that needs to be changed, because devServer is a function of webpack-dev-server, so we change the script in package.json and use webpack-dev-server to start

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

After this configuration, the browser automatically opens, and the page automatically refreshes when you modify the content

Implements CSS file parsing

First use NPM to install the following CSS-related dependencies

Less CSS-loader is used to parse the @import style-loader syntax, which inserts CSS into the head tag. Less-loader converts less to CSSCopy the code

If you report this error, the less version is a little too high

My version is as follows

"Less" : "^ 3.13.1", "less - loader" : "^ 6.2.0", "CSS - loader" : "^ 3.6.0", "style - loader" : "^ 1.3.0",Copy the code

Next we’ll add some styling to our program and create a new index.less under the SRC directory

#root {
  background-color: red;
  color: white;
  font-size: 50px;
  font-weight: bold;
}
Copy the code

Add index.less to index.js

import App from "./App.js";
import "./index.less";

document.getElementById("root").innerHTML = App.name;
Copy the code

At the command line

npm start
Copy the code

Click, the browser automatically opens, and the following output is displayed

Prefect !!!! This is a preliminary implementation of webpack to be able to parse JS, CSS projects

We can add to that

Enabling Hot Update

Why do YOU need hot updates

Hot update this function is very, very useful, if we don’t open a hot update, so we modify the project, the page will automatically refresh and display the content we want, but you think if your project becomes a super big, tens of thousands of lines of code, you are in your project add a console log, webpack can repackage, This is a very frightening, 😱, said he would pack less 1 minute, my god, you change a thing, he packed a minute, you have to wait a minute, page will refresh again, show the effect, it caused a huge waste of time, we do programmers, concerning work time to complete the task, home early from work, This is delaying everyone’s off work time ah, so we must embrace hot update, he will be partial refresh, not refresh the whole page, only change the part you modify, improve development efficiency, and I only said one of his advantages, other advantages see the following, love him there is no

What are the advantages of hot updates

Hmr-hot Module Replacement is one of the most useful features webPack provides. It allows various modules to be replaced, added, and removed at run time without having to completely refresh and reload the entire page

1. Retain the value of intPUT and do not re-enter it. Update only what is changed to save development time. 3. Style changes more quickly, almost the same as changing styles in the browser debuggerCopy the code

Start the hot update step

1. Add the hot update plug-in in webpack.config.js and enable hot in devServer

const webpack = require("webpack"); // Hot update plugin is a plugin that comes with Webpack... module.exports = { ... , plugins: [..., new webpack HotModuleReplacementPlugin (), / / the plugin class, so have to use the new], devServer: {... , hot: true, }, };Copy the code

If (module && module.hot) {module.hot.accept(); }

import App from "./App.js"; import "./index.less"; // After hot update is configured, the module will have hot property, and then we execute accept method in module.hot to tell the new module to use "partial refresh"; if (module && module.hot) { module.hot.accept(); } document.getElementById("root").innerHTML = App.name;Copy the code

Now try changing the contents of app.js to see if the page does not refresh, but only partially.

It’s really not easy for you to read this. I hope you can learn a lot. Don’t forget our slogan is “Driving webpack”.

Next time we will cover webPack construction: adding reference images to Webpack, setting up production mode and development mode configuration,

Refer to the article

  • Building Block (0)- Why do we need WebPack?
  • Why do we need Webpack?
  • [2.7W] React+Typescript project environment