Webpack first experience

Time:2021-10-21

Webpack basic usage

Entry of core concepts

Entry is used to specify the packaging entry of the webpack. Webpack is a module packer. In webpack, all resources (JS, CSS, HTML, pictures and fonts) will be regarded as modules. All these modules will have dependencies before. Therefore, webpack will start to look for dependencies from the entry file (specified by the entry), and there are other dependent files. In this way, a dependency graph is formed. For non code, such as pictures Font dependency will continue to be added to the dependency graph.

Entry usage
Single entry: entry is a string (single page application)

module.exports: {
  entry: './path/to/to/entry/file.js'
}

Multi entry: an entry is an object (multi page application)

module.exports={
  entry: {
    app: './src/app.js',
    adminApp: './src/adminApp.js'
  }
}

Output of core concept
Output is used to tell webpack how to output the compiled file to disk and the file name of the output and

Output usage: multi entry configuration
Whether it is single entry or multi entry, there is only one in output. How to output the packaged files corresponding to different entries is to use placeholders ([name]) to ensure the uniqueness of file names

module.exports = {
  entry: {
    app: './src/app.js',
    search: './src/search.js'
  },
  output: {
    filename: '[name].js',
    path: __dirname + '/dist'
  }
}

Core concept loaders

Webpack only supports JS and JSON file types out of the box. Other file types are supported through loaders and converted into effective modules, which can be added to the dependency diagram.

It is a function that accepts the source file as a parameter and returns the conversion result.

What are the common loaders?

babel-loader Convert the syntax of new JS features such as ES6 and ES7
css-loader Support CSS file loading and parsing
less-loader Convert less files to CSS
ts-loader Convert ts to JS
file-loader Package pictures, fonts, etc
raw-loader Import the file as a string
thread-loader Multi process packaging JS and CSS

Usage of Loaders
There will be multiple loaders in a webpack configuration, which need to be stored in the rules array of the module

const path = require('path')
module.exports = {
  output: {},
  module: {
    rules: [
      {test: / \. TXT $/, use: 'raw loader'} // test specifies the matching rule, and use specifies the loader name to use
    ]
  }
}

Plugins of core concept

Plug ins are used for bundle file optimization, resource management and environment variable injection. Anything loaders can’t do can be done with plugins.
Plugins acts on the entire build process.
Common pluginsWhat are there?

CommonsChunkPlugin It is often used for multi page packaging to extract the same module code of chunks into a public JS file
CleanWebpackPlugin Clean up build directory
ExtractTextWebpackPlugin Extract CSS from the bundle file into an independent CSS file
CopyWebpackPlugin Copy files or folders to the output directory of the build
HtmlWebpackPlugin Create an HTML file to host the output bundle
UglifyjsWebpackPlugin Compressed JS
ZipWebpackPlugin Generate a zip package from the packaged resources

Usage of plugins

module.exports = {
  output: {filename:'bundle.js'},
  plugins: [
    New htmlwebpackplugin ({template: '. / SRC / index. HTML'}) // put it in the plugins array
  ]
}

Mode of core concept

Mode is a concept proposed by webpack4. Mode is used to specify the current construction environment: production, development or none
You can use the webpack built-in function to set mode. The default value is production.

Built in function function of mode

development Set process.env.node_ The value of Env is development. Enable namedchunksplugin and namedmodulesplugin
production Set process.env.node_ The value of Env is production. Open flagdependencyusageplugin, flagincludedchunkplugin, modeconcatenationplugin, noemitonerrorplugin, occurentorderplugin, sideeffectsflagplugin and terserplugin
nonne Do not turn on any optimization options

Parsing ECMAScript 6 and react JSX

Resource parsing: parsing ES6
Using Babel loader

module.exports = {
  module: {
    rules: [
      {test: /\.js$/, use: 'babel-loader'}
    ]
  }
}

If a JS file is encountered, it will be parsed with Babel loader. Babel loader depends on Babel, so you need to use Babel’s configuration file. Babelrc in the project
Resource resolution: add the Babel preset configuration of ES6

{
  "presets": [
    "@ Babel / preset env" // add Babel preset configuration for ES6
  ],
  "plugins": [
    "@babel/proposal-class-properties"
  ]
}

Resource parsing: parse react JSX
Babel loader is also used, but the configuration of react needs to be added in the. Babelrc configuration file

{
  "preset": [
    "@babel/preset-env",
    "@ Babel / preset react" // add the Babel preset configuration of react
  ],
  "plugins": [
    "@babel/proposal-class-properties"
  ]`
}`

Resource parsing: parsing CSS
CSS loader is used to load. CSS files and convert them into commonjs objects
Style loader inserts the style into the head through the < style > tag

module.exports = {
  module: {
    rules: [
      {test: / \. CSS $/, use: ['style loader ','css loader']} // note that the calling of loader is a chain call, and the execution order is from right to left. Therefore, the CSS will be parsed with CSS loader first, and then the parsed CSS will be passed to style loader
    ]
  }
}

Parsing resources: parsing less and sass
Less loader is used to convert less into CSS

module.exports = {
  module: {
    rules: [
      {test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader']}
    ]
  }
}

Resource parsing: parsing pictures
File loader is used to process files

module.exports={
  module: {
    rules: [
     {test: /\.(png|svg|jpg|gif)$/, use: 'file-loader'}
    ]
  }
}

File listening in webpack

File listening is to automatically rebuild a new output file when the source code is found to have changed.
Webpack enables listening mode in two ways:
1. When starting the webpack command, bring the — watch parameter
2. Set watch: true in webpack.config.js

Principle analysis of file monitoring
Polling to determine whether the last editing time of the file has changed
If a file changes, it will not be immediately told to the listener. Instead, it will be cached first and wait for aggregatetimeout

module.exports = {
  //Default false
  watch: true,
  //Watchoptions is meaningful only when listening mode is enabled
  watchOptions: {
    //It is empty by default. It does not listen to files or folders. Regular matching is supported
    ignored: /node_modules/.
    //After listening to the change, it will wait 300ms for execution. The default is 300ms
    aggregateTimeout: 300,
    //Whether the file changes is determined by constantly polling the system to specify whether the file has changed. By default, it is asked 1000 times per second
    poll: 1000
  }
}

Hot update in webpack and its principle analysis