What is Webpack?

This article code execution environment: Node 10 above, WebPack 4 aboveCopy the code

1. The concept

Webpack website

Definition of official website:

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.Copy the code

In plain English:

1) Look at your project

  • There are various file formats:.vue,.js,.css/less/scss/sass, pictures, font ICONS…
  • Uses the ES6/7/8 syntax or feature, as well as more advanced syntax
  • bulkynode_modules
  • The SRC folder contains a surprising number of business code files
  • Cross-domain issues in the development environment, solved when the hair caught bald
  • Console explosion, click in and found that the source code is not the same as their own
  • Every time you change your code, you have to manually refresh the browser and style it until your scalp is tingling
  • Deployment line, squatting company, king hit no electricity, the moon west oblique, the project is still packaging
  • .

2) Think about it

  • How long would it take to upload this amount of files directly to the server?

  • How long do users have to wait for browsers to read so many JS files one by one, analyze them one by one, combine so many CSS files one by one, and finally assemble them in front of them?

  • Es6/7/8 and other advanced syntax browser do not know, how to do?

3) Then, all of a sudden, webPack handles all of these problems with ease. As is shown in

In this picture, Webpack does a lot of work

  • There are many kinds of files and complex business codes. Webpack merges modules through analysis and dependency, and compreses them after classification, reducing the size of files
  • Advanced/emerging syntax, Webpack for code validation, translation, and browser – aware JS
  • Considering the speed pain point, WebPack uses an advanced approach when analyzing dependencies, greatly increasing them
  • node_modulesIt’s so bulky that webPack will intelligently ignore some of the parts you don’t use and speed up the packaging as soon as you tell it to
  • Webpack is also packaged with code split/split and multi-module sharing to prevent repeated analysis/loading

For the pain points/problems listed above, thoughtful Webpack also solves them

  • Webpack allows the browser to refresh automatically, and partially, allowing you to see code changes in real time
  • Cross-domain problems in the development environment are easily solved through webPack configuration
  • SPA apps, through on-demand loading, lazy loading, code segmentation, dynamic packaging using cache, can greatly speed up the first screen speed, so that your users will not have to wait

With all the text above, you should now have a clear idea of what WebPack does and what it does.

Any concept in the world is defined by its nature, its scope of application, its effect.

Do you already have the concept of Webpack in mind?

2. Core composition

  • Entry
  • Output
  • loaders
  • The plug-in (Plugins)
  • Mode (Mode: development or production)
  • Browser Compatibility (New in WebPack5.0)
  • Environment (Added in WebPackage 5.0)

To start the configuration, you need to create a webpack.config.js file in the root directory

2.1 Inlet and outlet

Note only two points in the configuration of the two: The number of entrances and exits corresponds to each other, and the path of the entrances and exits

Consistent quantity: one entrance VS one exit, multiple entrance VS multiple exit

2. An entrance: a relative path; Exit: Absolute path

To ensure the accuracy of the path, you need to use the built-in Path module of Node, directly require

Const path = require('path') // Webpack configuration files follow the CommonJS specification. What is the ommonJS specification? Module.exports = {entry: './ SRC /main.js', output: {// path.resolve() : // path.join () : used for path joining // Output must be an absolute path, otherwise an error is reported // Path. The resolve (__dirname, '/ dist/'), / / method 2: path: the path. The join (__dirname,'/dist/'), filename: 'bundle. Js / / specified filename} after packaging,}Copy the code

2.2 loaders

Webpack only handles JS files by default, other non-JS files need to be loaders

(1) Pay attentionloadersExecution order: bottom to top, right to left

During normal configuration, check the rules before and after the use of each loaders; otherwise, an error message will be displayed

(2) Can their execution order be manually intervened?

Yes, add enforce after use

Enforce Optional value: pre: in advance. Post: the rear

(3) All types of WebpackloadersPre > inline > Normal > POST

Inline refers to a situation in which a module uses syntax such as “import” to import the module separately

(4) General configuration

In the absence of advanced syntax

loadersIn the earlier version of Webpack, it was written differently. Versions 4 and 5 are written the same

Module level with entrance and exit:

module : [ rules : [ {test:// , use:[]/''} ]
Copy the code

In the following code, urL-loader is used to process and classify pictures. After packaging, the pictures in the project will be centralized in the configured folder, which reflects the compression and classification function of Webpack

Must remember!!

  • NPM install the package first, and then configure it

  • Exclude: /node_modules/ Ignore the parsing, validation, and translation of this folder.

module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist/'), filename: Rules: [{test: /\.css$/, use: ['style-loader', 'css-loader']}, {test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] }, { test: /\.s(a|c)ss$/, use: ['style-loader', 'css-loader', 'sass-loader']}, // url-loader Just url - loader is much more than the latter can be set up the options {test: / \. (JPG | jpeg | PNG | BMP | GIF) $/, use: {loader: 'url - loader, the options: {limit: OutputPath: 'images', //dist create images folder name: '[name], [4] hash: [ext]' / / picture filename + hash value of four digits, ext: the original suffix}}}, {test: / \. (woff | woff2 | eot | SVG | the vera.ttf) $/, use: 'url-loader' }, { test: /\.js$/, use: { loader: 'babel-loader', // options: { // presets: ['@babel/env'], // plugins: [ // '@babel/plugin-proposal-class-properties', // '@babel/plugin-transform-runtime' // ] // } }, exclude: /node_modules/, } ] }, }Copy the code

(5) Babel is not to be ignored

Advanced syntax case

Babel’s primary purpose is translation, translating high-level syntax into browser-aware syntax

As the project grows, you may find yourself using a lot of loaders and plugins from the Babel family, so it is recommended that we create a.babelrc file in the root directory to configure the Babel family

One particular point to note:

After the configurationbabel-loaderAfter that, the project can convert ES6 syntaxes such as class definition classes, but the new prototype method [].inculdes(), which Babel does not convert by default, needs to install a patch called Polyfill

npm i @babel/polyfill -S
Copy the code

Configure at the entrance

entry: ['@babel/polyfill', './src/main.js'],
Copy the code

Alternatively, introduce where the new method is used:

import '@babel/polyfill'
Copy the code

Webpack officially said that this patch will be removed after 5.x, it seems that the update has not been removed after a cursory. please let me know what happened to this patch

2.3 plug-in (Plugins)

Plug-ins do what loader can’t do!

Steps:

  • NPM to pack
  • Webapck official website view your package how to configure

This piece, really do not know do not know what to say, on the above figure to demonstrate the configuration position

Plugins are level with entrances and exits

const path = require('path') module.exports = { entry: './src/main.js', output: { path: Path.resolve (__dirname, './dist/'), filename: 'bundle.js', module: {rules: [{test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] }, { test: /\.s(a|c)ss$/, use: ['style-loader', 'css-loader', 'sass-loader']}, // url-loader Just url - loader is much more than the latter can be set up the options {test: / \. (JPG | jpeg | PNG | BMP | GIF) $/, use: {loader: 'url - loader, the options: {limit: OutputPath: 'images', //dist create images folder name: '[name], [4] hash: [ext]' / / picture filename + hash value of four digits, ext: the original suffix}}}, {test: / \. (woff | woff2 | eot | SVG | the vera.ttf) $/, use: 'url-loader' }, { test: /\.js$/, use: { loader: 'babel-loader', // options: { // presets: ['@babel/env'], // plugins: [ // '@babel/plugin-proposal-class-properties', // '@babel/plugin-transform-runtime' // ] // } }, exclude: // node_modules/,}]}, plugins: new CleanWebpackPlugin(), new CopyWebpackPlugin([{from: path.join(__dirname, 'assets'), to: 'assets' }]), ], }Copy the code

Specifically will be the whole code affixed, so that small lovely people have an intuitive understanding.

Ii. Webpack Advanced Configuration (Performance optimization direction)

It’s a combination of loaders and plug-ins

I’m so hungry. I’m gonna go eat. I’ll fill it up later