What is a webpack

Webpack is a packaging tool whose purpose is that all static resources can be packaged. One might ask why webpack? Webpack is the cornerstone of modern front-end technology, and conventional development methods such as jquery, HTML, and CSS static web development have fallen behind. This is the age of MVVM, data-driven interfaces. What Webpack does is analyze the structure of your project, find JavaScript modules and other extensions that browsers don’t run directly (Less, TypeScript, etc.), and package them into a format that browsers can use.

The installation of the webpack

The premise condition

Before installing WebPack, make sure you have the latest version of Nodejs installed.

The local installation

To install the latest version or a specific version, run one of the following commands:

NPM install --save-dev webpack # or specify the version NPM install --save-dev webpack@<version> // --save-dev can be shortened to -dCopy the code
Tip

Whether to use –save-dev depends on the business application scenario. Assuming you only use Webpack for build operations, it is recommended that you use the –save-dev option at install time, since you may not need webpack in production. Ignore the –save-dev option if you want to apply it to production environments.

Global installation

Webpack can be made available in a global environment with the following NPM installation:

NPM install --global webpack // --globalCopy the code

Core WebPack concepts

1. Entry: Indicates which module WebPack should use as a starting point for building its internal dependency Graph. Once at the entry point, WebPack finds out which modules and libraries are (directly and indirectly) dependent on the entry point.

Output: Tells WebPack where to Output the bundles it creates and how to name them. The default value for the main output file is./dist/main.js, and the other generated files are placed in the./dist folder by default.

3. Loader (module converter) : Webpack can only understand JavaScript and JSON files, which is available out of the box with WebPack. Loader enables WebPack to process other types of files and convert them into valid modules for use by applications and to be added to dependency diagrams.

4. Plugins: Loaders are used to transform certain types of modules, while plug-ins can be used to perform a wider range of tasks, injecting extension logic at specific points in the Webpack build process to change the build result or do what you want. Including: package optimization, resource management, injection of environment variables.

5. Module: In modular programming, developers break up programs into chunks with discrete functions, called modules.

Each module corresponds to a file in Webpack, and WebPack recursively finds all dependent modules starting from the configured Entry.

Webpack simple packaging cases

First, preparation

Create an empty folder to create the project. Here I create a local folder named static_demo, use the terminal to access the folder and use the NPM init command to initialize a package.json file. After you type this command, the terminal will ask you a list of information such as project name, project description, author, etc., but if you don’t want to publish the module, just press Enter. (You can also use the command NPM init -y to generate package.json file once, so that the terminal will not ask you questions, easy to process, I directly input NPM init -y command).

Install webPack

Next, type the following command on the command line to install webpack. If you want to do it all at once, install both the global webPack and the local project webpack first, since some modules will need it later.

NPM install webpack -g // Install global webpack command NPM install webpack webpack-cli -d // Install local project modulesCopy the code

Create a file

Create two new folders in the static_demo folder, SRC and Build, add the index.js and data.json files in SRC, and add the index. HTML file in build. The project structure is as follows

Json module in index.js. The contents of the index.js file are as follows:

Import data from './data.json' console.log(data) function add(x, y) {return x + y} console.log(add(1,2))Copy the code

Import the packaged js file main.js under index.html

<! 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 </title> </head> <body> <h1 id="title"> Hello webpack</h1> <script src="./main.js"></script> <! </body> </ HTML >Copy the code

4. Execute the package command

Enter the command line at the terminal to perform packaging

// If webpack is installed globally, Js -o./build --mode=development // --output can be shortened to -o // The above command is equivalent to packaging the index.js file from the SRC folder into the main.js file from the build folder. This generates the packaged file for index.html to importCopy the code

As you can see, Webpack compiles both index.js and data.json, since the index.js file introduces the data.json module, now open index.html and see the result

We have successfully used webpack for packaging, but I am tired of typing such a long command in the terminal. Next, we will learn to use Webpack through configuration files

Use WebPack through configuration files

Create a new configuration file, webpack.config.js, in the root directory of the current project, and write the following simple configuration code, which so far involves only the entry configuration (which is equivalent to our index.js, from which we package), the exit configuration (which is equivalent to our generated main.js), and the mode configuration.

Const {resolve} = require('path') module.exports = {// webpack exports = {// webpack exports = {// webpack exports = {// webpack exports = {// webpack exports = { // webpack pack entry: './ SRC /index.js', 'main.js', // output path // --dirname is a global variable of Node.js, indicating the current script directory path: resolve(__dirname, 'build')}, // loader configuration module: []}, plugins: []}, // The default mode is production mode: 'development' }Copy the code

With this configuration file, we can pack by simply running the webpack command in the terminal, which automatically references the configuration options in the webpack.config.js file

6. Customize script commands in package.json files

Node projects typically have a package.json file that describes the current project and has a scripts property that allows you to customize script commands, such as the package command we ran. You can add custom scripts to scripts:

Then you can use NPM run build to run the script command. What’s the benefit? If the command line is short, the benefit is not obvious, but how can the command line be long? So here we can add the command that needs to be executed every time. After scripts is configured, the NPM run key value is equivalent to running value on the terminal