Webpack is essentially a static module bundler for Javascript applications. When an application is processed by Webpack, it recursively builds a diagram that the entire application depends on, starting from the entry file, containing every module the application needs. All of these modules are then packaged into one or more bundles.

Core Webpack concepts

Webpack is a package modular Javascript tool, in Webpack all files (HTML, JS, JSX, LESS, CSS, pictures) are modules, into Webpack module combination packaging processing to generate browsers can directly use static resources; Generally speaking, if you want to use Webpack, you need to understand the packaging principle of Webpack, as well as the meaning and use rules of each configuration item; The main core concepts of Webpack include Entry, Output, Module, resolve, plugins, etc.

Install Webpack globally

npm install webpack webpack-cli -g
Copy the code

Partial installation of Webpack

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

Usually when we execute Webpack directly from the command line, we execute the Webpack command of the current global installation. When we want to use Webpack installed inside the project, we can execute the Webpack command by defining the script in the package.json file. We recommend using local commands in a project to prevent conflicts caused by different versions of dependencies required by the project.

script: {
  "build": "Webpack"
}
Copy the code

By default, Webpack reads the configuration from the webpack.config.js file at the root of the project when it executes the build. You can also specify the configuration file name with the command line argument –config; Since the Webpack build runs in node.js, the file finally needs to export an Object describing how to build it through the CommonJS specification

Entry

Configure module entry; Specify the starting point for Webpack to perform the build as a starting point for building its internal dependency diagram. Can be single entry or multiple entry:

Entry: String | Array | Object<String | Array>

/* * String Single entry, single exit * This is the simplest and most common way to configure the entry starting point. Webpack builds the dependency graph recursively from this main entry file, and eventually packs to produce a chunk output */
module.exports = {
  entry: "./main.js"
}

//Array multiple entries, but also generates a single export file after packaging
module.exports = {
  entry: ["./main1.js"."./main2.js"]}/* * Object multiple entries, each entry generates a Chunk * the most configurable, */

module.exports = {
  entry: {main1: "./main1.js".main2: "./main2.js"}}Copy the code

Output

Configure how to output the desired code. Output is an Object containing a series of configuration items. Here are some of them:

Path: specifies the address of the directory where the file is stored. The absolute path must be /dist by default

Filename: filename generated by packaging. Placeholders can be used together with entry

Placeholder name meaning
id Unique identification of the module, starting from 0
name The name of the module
hash Hash this time
chunkhash Hash of chunk content

The length of [hash] and [chunhash] can be specified. [hash:8] indicates the 8-bit hash value. The default value is 20 bits

PublicPath: Configures the URL prefix of online resources. This configuration item is required when the packaged and generated resource files are hosted on the CDN. We may not know the publicPath of the output file when we write the configuration file in the early stage. We can leave it blank and set it directly in the entry file using the free variable __webpack_public_path__

module.exports = {
  output: {path: the path. The resolve (__dirname,'./dist'),
  	filename: 'bundle.js'}}Copy the code

CrossOriginLoading: Some code blocks output by Webpack may need to be loaded asynchronously, which is realized by JSONP. The principle of JSONP is to dynamically insert a tag into HTML and load cross-domain resources through SRC. CrossOriginLoading is used to set this value:

  • False: Forbid cross-domain loading (default)
  • Anonymous: The user’s Cookies are not taken with this script resource when it is loaded
  • Use-credentials: The Cookies of the user are taken with this script resource when it is loaded

Module

Configure processing module rules; Webpack can only handle JS or JSON files by default. How do you handle these other types of files

Rules: configures the read and parse rules of the module, which is usually used to configure the Loader. For other types of files, you need to use various Loaders to convert them into files that Webpack can handle, and then build the packaged output. This allows us to package any resource other than JavaScript; Commonly used loader

file-loader

The file is directly output to the specified folder without any processing, and the relative URL is returned. The output file name can be configured

module: {
	rules: [{test: /\.(png|jpg|jpeg)$/,
      use: {
        loader: 'file-loader'.options: {
          name: [name]-[hash].[ext] ,
          outputPath: 'imgs'.publicPath: 'assests/'}}}]}/** placeholder * name: the original name of the resource file * Hash: the hash generated from the file contents * ext: the resource file extension */
Copy the code

url-loader

Functions like file-loader, but returns base64 DataURL if the file size is below the specified limit. If the value is larger than the specified limit, it has the same function as file-loader. The file is directly exported to the target folder without any processing.

module: {
	rules: [{test: /\.(png|jpg|jpeg)$/,
      use: {
        loader: 'url-loader'.options: {
          limit: '1024'}}}]}/** placeholder * name: the original name of the resource file * Hash: the hash generated from the file contents * ext: the resource file extension */
Copy the code

CSS related loader

Less-loader: converts less to CSS CSS-loader: converts CSS to CommomJs module Style-loader: creates style labels and adds CSS to the pageCopy the code

NoParse: Improves build performance by allowing Webpack to ignore and skip files that are not modularized.

Resolve (resolve)

Configure finding module rules and set how modules are parsed. Resolve configures how Webpack finds the files for the modules that depend on it, starting from the configured entry module.

alias

Aliases for common paths can reduce the time for module path resolution and facilitate file reference in different places

module.exports = {
	resolve: {
		alias: {
      "react": '/node_modules/react/react.min.js'}}}Copy the code

Extensions: Webpack will automatically add extensions to import statements without file extensions to try to access the existing file. Default [‘.js’, ‘.json’]

Modules: Configure Webpack to find third-party modules in those directories, the default node_modules folder

devtool

Controls whether and how source maps are generated; Different formats of source map values can significantly affect the speed of builds and rebuilds

So what is the Source Map? Typically, the code we use to deploy to production is compressed (removing unnecessary strings like comments, whitespace, newlines, and so on) to reduce the size of the code. When the code goes wrong, we can’t quickly locate the problem on the console, which is the problem source Map is trying to solve.

plugins

Plugins are simple to configure. Plugins receive an array of items, each of which is an instance of the Plugin to be generated using the new keyword. The parameters needed by Plugin ‘are passed in through the constructor. Some commonly used plug-ins:

html-webpack-plugin

clean-webpack-plugin

DevServer

DevServer starts an HTTP server to service web requests, helps start Webpack, receives file changes from Webpack, and automatically refreshes web pages through WebSocket protocol for real-time preview.

Host: Specifies the host to use

Port: specifies the listening port

Proxy: Configures the service proxy

Hot: Enables module hot replacement. The default behavior of DevServer is to preview the source code in real time by automatically refreshing the entire page when it is updated. With hot module replacement enabled, it will preview the source code in real time by replacing the old module with a new module without refreshing the entire page

ContentBase: devServer.contentBase Configures the file root directory of the devServer, which by default is the current execution directory (that is, the directory where the configuration files are located).

Open: The default browser is automatically opened after the service is started

Compress: Enable gzip for each static file. The value is Boolean and the default value is false