preface


Recently, I have been learning Webpack, and I have also learned Webpack knowledge intermittently before, but it is always scattered, so I want to make a learning summary here, so let’s start


What is a Webpack

Let’s take a look at the official definition:

In essence, Webpack is a static Module bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a Dependency graph containing every module the application needs, and then packages all of those modules into one or more bundles

To put it simply, Webpack is a modern JavaScript module packaging tool that resolves dependencies among modules and organizes modules together according to specific rules and order, and eventually merges them into one or more JS files. This process is module packaging.

We can think of Webpack as a module factory. It takes the source code, processes it and other operations, and finally produces the resource file, waiting for delivery to the user.

Meaning of using Webpack

In Web development, we usually use nothing but HTML, CSS, JS and other static resources, so why don’t we directly publish the source files in the project to the server but to the Webpack for processing? In fact, it is no problem to develop a simple Web application (faintly remember the story of some big guy using notepad directly before) because the previous demand is very simple, but when the application scale is large, it must have the help of certain tools, the so-called work is good, must first sharpen its device is this truth.

So what’s the point of using Webpack? What I understand is that it allows us to develop applications in a modular way

What is a module

In fact, we deal with modules all the time, an NPM package, a JS file we can call a module. We can think of modules as different departments in a hospital, each of which has its specific function, and each department works together to make the hospital run normally.

Js module development

In fact, at the beginning of JS design, there is no such concept as module. If there are multiple JS files in the project, we can only insert them into the page one by one through javaSript tags. However, with the continuous development of business, it is more and more difficult to manually maintain the JS loading order, and the top-level scope of each script tag is the global scope, if there is no processing directly in the code variable or function declaration, it will cause global scope pollution. Modularity solves these problems.

Modular specification

(1) common. Js

  • Each file separately divided into a module, and the original documents are in a different way, introduced use script form, script is the top-level scope is the global scope, may be contaminated when variable declarations are global variables, while the latter can form a module’s scope, all variables and functions themselves can only access
  • An internal module object holds information about the current module. Module.exports specifies what to expose
  • The module uses require for method import

(2) ES6 Module

  • ES6 Module also takes each file as a Module, each Module has its own scope, the difference is import, export statements. Import and export have also been added as reserved keywords, as import and export keywords.
  • There are two export modes: named export and default export

(3) the AMD

  • It is proposed by the JS community that both focus on and browser-side modularity are standard, and the biggest difference between it and the previous two approaches to both modules is that it is asynchronous.

  • Modules are defined in AMD using the define function, which takes three arguments. The first parameter is the current module id, which is equivalent to the module name. The second parameter is the dependency of the current module, and the third parameter describes the value that the module exports, which can be a function or an object. If it is a function, then all exports return values; If it is an object, export the object itself. If you need to export members from the current module, you can return them.

    AMD define([], function() {return {}})Copy the code

(4) the UMD

  • Strictly speaking, UMD is a set of modular forms. Common module standards all aim to enable a module to operate in a variety of environments

How do I start a Webpack project

The premise condition

Webpack has certain requirements on the node.js > version, and it is recommended to use Node.js LTS (Long Term Suppor Maintenance). Using the new version of Node and the new version of Webpack can greatly improve the performance optimization, up to 90% faster than the old version. Therefore, the latest stable version is recommended.

The installation

With a global installation, when working with others, the output may be inconsistent due to the different versions of WebPack on each person’s system. Plug-ins that are partially dependent on WebPack call modules within webPack in your project, which still need to be installed locally, which can cause confusion if they are both local and global

So here we choose to install Webpack inside the project. Start by creating and initializing a project on your desktop

Mkdir webpackDemo CD webpackDemo NPM init or # yarn initCopy the code

Next, execute the Webpack installation command

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

So there you have it, Webpack is the core module we’re going to use, webpack-CLI is the command line tool. To check whether the installation is successful, use NPX webpack -v. NPX webpack cli – v. If the version number is displayed, the installation is successful. Why NPX? Since we have webpack installed locally, we can’t use webpack directly from the command line. NPX will help us find Webpack in the node_modules directory of our current project.

Package the first application

First we create index.html, SRC folder in the project root directory. Create the index.js file and the hello-world.js file in the SRC folder

touch index.html
mkdir src
cd src
touch index.js
touch hello-world.js
Copy the code

index.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, /> <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge" /> <title>My first webpack app</title> </head> <body> <script src="./dist/bundle.js"></script> </body> </html>Copy the code

index.js

import HelloWorld from "./hello-world";

document.write("My first webpack app <br />");
HelloWorld();

Copy the code

hello-world.js

export default function() {
  document.write("Hello World");
}
Copy the code

At this point we use commands

npx webpack
Copy the code

When you open the index.html file, you’ll see it on the page

My first webpack app
Hello World
Copy the code

Configuration webpack

First of all, we need to know that Webpack cannot package your project directly. If you can package your project directly, the WebPack team does the configuration file by default. Now we will write a basic configuration file ourselves. And add code:

module.exports = {
  entry: "./src/index.js",
  output: {
    filename: "bundle.js"
  },
  mode: "development"
};
Copy the code

When using React or vue, we usually use the NPM run command to pack webpacks. Then we configure the NPM script

In package.json file

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

Now let’s delete the dist package and run the command again

npm run build
Copy the code

We see that WebPack executes the package command and regenerates the dist package file

webpack-dev-server

Every time you change the file, you have to repackage it, which feels inefficient. Instead of just editing the project and refreshing it, now there’s an extra step of packaging. So how do you optimize? The community has provided us with a quick native development tool, Webpack-dev-server. Install with the following command:

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

After installation we add the script configuration file to package.json

"scripts": {
     "build": "webpack",
   + "dev": "webpack-dev-server"
  }
Copy the code

Finally, we need to configure webpack.congif.js

module.exports = { entry: "./src/index.js", output: { filename: "bundle.js" }, mode: "development", devServer: {publicPath: "/dist"}};Copy the code

Webpack-dev-server can be thought of as a server whose main task is to accept browser requests and return resources. When the service is started, webpack is first used to pack the modules and prepare the resources (in this case the resource file is bundle.js). When webpack-dev-server accepts the browser request, it performs the URL verification first. If the address is a resource service address (which we configured as publicPath), the resource is retrieved from the WebPack package and returned to the browser. Conversely, if the requested address does not belong to the resource service address, it will be read directly from the hard disk when the source file will be returned, so this is why sometimes when you open the index.html file the source file will be returned.

And then we execute

npm run dev
Copy the code

The command line displays an Error message: Cannot find module ‘webpack-cli/bin/config-yargs’ Cannot find module ‘webpack-cli/bin/config-yargs’ This is due to the new version of webpack-cli is not compatible with the webpack-dev-server version.

"Webpack" : "^ 5.6.0," "webpack - cli" : "^ 4.2.0", "webpack - dev - server" : "^ 3.11.0"Copy the code

Let’s first remove webpack-Cl and then install the specified version

NPM uninstall webpack-cli -d NPM install webpack-cli@^3.3.12 --save-devCopy the code

When we execute the command, we will find that WebPack is running properly. Open the local ULR and see that the page is displayed normally.

Or just use:

"scripts": {
   - "dev": "webpack-dev-server"
   + "dev": "webpack-dev-server --open"
  }
Copy the code

conclusion

After watching Webpack basics we have a basic understanding of Webpack, know what it is, what it can do, how to use Webpack for project development, know the basic usage of webpack-dev-server. Now that the basics have been set up, we are ready to move on to the advanced Webpack chapter, where we begin to understand how to use and write modules to further deepen our understanding of Webpack

Related series

Webpack advanced