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. In short, Webpack is a tool for building based on dependencies, while gulp and Grunt are streamlined packaging tools.

The advantage of webpack

1, code split (support asynchronous module loading)

Webpack has two ways of organizing module dependencies, synchronous (the default) and asynchronous (advanced). Asynchronous dependencies act as split points, forming a new block. After optimizing the dependency tree, each asynchronous block is packaged as a file.

2, Loader (support any module loading, such as images, less, CSS, etc.)

Webpack itself can only handle native JavaScript modules, but loader converters can convert various types of resources into JavaScript modules. In this way, any resource can become a module that Webpack can handle.

3. Intelligent parsing

Webpack has an intelligent parser that can handle almost any third party library, whether they come in the form of modules such as CommonJS, AMD, or plain OLD JS files. Even when loading dependencies, you can use the dynamic expression require(“./templates/” + name + “.jade”).

4. Plug-in system

Webpack also has a feature-rich plug-in system. Most of the content functions run on this plug-in system, and open source Webpack plug-ins can be developed and used to meet a variety of needs.

5. Run fast

Webpack uses asynchronous I/O (NodeJs) and multiple levels of “caching” for efficiency, which allows Webpack to compile increments at an incredibly fast rate.

Basic concepts of Webpack

Entry

Entry Point __ 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

The Output attribute tells WebPack where to export the bundles it creates and how to name those files. 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.

You can configure these processes by specifying an output field in the configuration

Loader

Webpack can only understand JavaScript and JSON files, which is a built-in capability of WebPack available out of the box. 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.

Plugin

Loaders are used to transform certain types of modules, while plug-ins can be used to perform a wider range of tasks. Including: package optimization, resource management, injection of environment variables.

Webpack packaging principles

The running flow of Webpack is a sequential process, from start to finish:

  1. Initialization parameters: Read and merge parameters from configuration files and Shell statements to arrive at the final parameters.
  2. Start compiling: Initialize the Compiler object with the parameters obtained in the previous step, load all configured plug-ins, and execute the object’s run method to start compiling.
  3. Identify entry: Locate all entry files according to the entry in the configuration.
  4. Compiling modules: Starting from the entry file, call all configured Loader to translate the module, find out the module that the module depends on, and then recurse this step until all the entry dependent files have passed this step.
  5. Complete module compilation: After using Loader to translate all modules in Step 4, the final content of each module after translation and the dependencies between them are obtained.
  6. Output resources: Assemble chunks containing multiple modules one by one according to the dependency between the entry and modules, and convert each Chunk into a separate file and add it to the output list. This step is the last chance to modify the output content.
  7. Output complete: After determining the output content, determine the output path and file name based on the configuration, and write the file content to the file system.

In the above process,Webpack will broadcast a specific event at a specific point in time, the plug-in will execute a specific logic after listening for the event of interest, and the plug-in can call the API provided by Webpack to change the running result of Webpack.

Webpack configuration

Webpack installation

npm install -g webpack

Initialize the package.json file

npm init

The use of webpack

webpack {entry file} {destination file}

webpack.config.js
module.exports = {
	entry: __dirname +"/app/main.js",
	output: {
		path: __dirname +"/public",
		filename: "bundle.js"
	}
}
Copy the code

You can use the webpack directive after you have a configuration file (non-global node_modules/.bin/webpack)

Webpack a common loader
  • Styles: style-loader, CSS-loader, less-loader, and Sas-loader
  • Files: raw-loader, file-loader, urL-loader, etc
  • Compile: babel-loader, coffee-loader, TS-loader, etc
  • Verification tests: Mocha-loader, jshint-loader, ESlint-loader, etc
A plugin commonly used by WebPack
  • First webPack is built inUglifyJsPlugin, compress and obfuscate code.
  • Webpack built-inCommonsChunkPlugin, improve packaging efficiency, and package third-party libraries and business code separately.
  • html-webpack-pluginYou can automatically generate HTML code from templates and reference CSS and JS files
  • extract-text-webpack-pluginSeparate styles referenced in the JS file into a CSS file
  • DefinePluginGlobal variables are configured at compile time, which is useful for development mode and release mode builds to allow different behavior.
  • HotModuleReplacementPluginHot update
  • optimize-css-assets-webpack-pluginDuplicate CSS in different components can be quickly de-duplicated
  • compression-webpack-pluginThe production environment can use GZIP compressed JS and CSS

A quick note on webpack’s hot update:

Hot updates are mechanisms in the application’s development environment that allow developers to modify the code without refreshing the page and visually see the changes on the page.

Principle of thermal renewal
  • useexpressStart a local service that responds when the browser accesses the resource.
  • Used by the server and clientwebsocketLong connection
  • webpackListen for changes to the source file, which is triggered when the developer saves the filewebpackRecompile.
    • This is generated every time you compileHash value,The JSON file of the module has been modified,Js file that has changed the module code
    • Pass after compilingsocketPush the currently compiled to the clientHash stamp
  • The client’swebsocketI’m listening for a file change pushHash stampWill be compared to the last time
    • If they are consistent, the cache is removed
    • If not, passajaxandjsonpObtain the latest resources from the server
  • useMemory file systemLocal refresh to replace modified content

The usage method is as follows:

//HotModuleReplacementPlugin(); module.exports = { // ... devServer: { hot: true, // ... }}Copy the code