oneWebPack
1.1. Webpack profile
Webpack is a front-end resource builder, a static Module bundler. When WebPack works with an application, it internally builds a dependency graph that maps to each module required for the project and generates one or more bundles.
Knowledge:
1.2. Core concepts of Webpack
1.21. Entry
The Entry indicates which file webPack starts packing as the Entry point, analyzing and building the internal dependency diagram.
1.22. The Output
Output indicates where the resource bundles Output from WebPack go and how to name them.
1.23. Loader
Loader enables Webpack to handle non-javascript files (Webpack can handle JS/JSON resources)
1.24. The Plugins
Plugins can be used to perform a much wider range of tasks. Plug-ins range from packaging optimization and compression,
All the way to redefining variables in the environment and so on.
1.25. Mode
Mode instructs Webpack to use the configuration of the corresponding Mode
options | describe | The characteristics of |
---|---|---|
development | The process.env.node_env value in DefinePlugin is set to development | Development environment (allows code to be debugged locally) |
production | By default, the process.env.node_env value in DefinePlugin is set to production | Production environment (an environment where code can be optimized to run online) |
none | Do not use any default optimization options |
1.26. Browser compatibility
Webpack supports all ES5-compliant browsers (IE8 and below are not supported). The import() and require.ensure() of Webpack require promises. If you want to support older browsers, you also need to load Polyfill before using these expressions.
1.27. The environment
Webpack 5 runs on version 10.13.0+ of Node.js.
1.3. Perform initial configuration
-
Initialization package. Json
Input instruction: NPM initCopy the code
-
Download and install webPack
Enter command: NPM install webpack webpack-cli -g NPM install webpack webpack-cli -dCopy the code
1.4. Compile and package applications
-
Create a file
-
Operation instruction
-
Development environment directive: webpack SRC /js/index.js -o build/js/ built-in –mode=development
What it does: WebPack compiles packaged JS and JSON files and converts es6’s modular syntax into a syntax that browsers can recognize.
-
Production environment directive: webpack SRC /js/index.js -o build/js/ built-in –mode=production
Function: in the development of configuration function on a function, compression code.
-
-
Webpack compiles packaged JS and JSON files. The ability to translate es6’s modular syntax into a syntax that the browser can recognize. Can compress code.
-
Webpack cannot compile and package CSS, IMG and other files. Js basic ES6 syntax cannot be converted to es5 syntax.
1.5. Basic configuration of the WebPack development environment
1.51. Configuration file webpack.config.js
Run instruction: webpack
// loader downloads the configuration
// plugins download import configuration
const { resolve } = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
/ / webpack configuration
/ / the entry
entry: "./src/index.js"./ / export
output: {
// Output the file name
filename: "built.js".// Output path
// __dirname indicates the absolute path of the current file directory
path: resolve(__dirname, "build"),},/ / a loader configuration
module: {
rules: [
// Which files to match
{
test: "/.css$/".// Which loaders are used for processing
// style-loader creates a style tag, inserts js style resources, and adds them to the head to take effect
// css-loader turns CSS files into commonJS modules and loads them with style strings
// Execute from right to left
use: ["style-loader"."css-loader"],},// Details loader configuration],},// Plugins are configured
plugins: [
new HtmlWebpackPlugin({
// Copy the file './ SRC /index.html' and automatically import all the resources (JS/CSS) that are packaged as output.
template: "./src/index.html",})],/ / mode
// Development mode
// Production environment
mode: "development"};Copy the code
1.52. Package style resources
1.Download and install the loader package NPM I CSS-loader style-loader less-loader less-d2.Modifying a Configuration Filemodule: {
rules: [
// Which files to match
{
test: "/.css$/".use: ["style-loader"."css-loader"],}, {test: "/.less$/".use: ["style-loader"."css-loader"."less-loader"]],}},Copy the code
1.53. Package HTML resources
1.NPM install --save-dev html-webpack-plugin2.Modifying a Configuration Fileconst HtmlWebpackPlugin = require('html-webpack-plugin');
{
plugins: [
new HtmlWebpackPlugin({
// Copy the file './ SRC /index.html' and automatically import all the resources (JS/CSS) that are packaged as output.
template: "./src/index.html",})],}Copy the code
1.54. Package image resources
1.NPM install --save-dev html-loader url-loader file-loader// Problem: img images in HTML cannot be processed by default
// Process image resources
test: /\.(jpg|png|gif)$/.// Use a loader
// Download url-loader file-loader
loader: 'url-loader'.options: {
// Images smaller than 8KB will be base64 processed
// Advantages: reduce the number of requests (reduce server stress)
// Disadvantages: Larger image size (slower file request)
limit: 8 * 1024.// Problem: Because url-loader uses ES6 modular parsing by default, htMl-loader imports images by commonJS
[object Module]
// Resolve: Disable ES6 modularization of urL-loader and use CommonJS parsing
esModule: false.// Rename the image
// [hash:10] takes the first 10 bits of the hash of the image
// [ext] takes the original extension of the file
name: '[hash:10].[ext]'
},
{
test: /\.html$/.// Handle the IMG image of the HTML file (responsible for importing img so that it can be processed by urL-loader)
loader: 'html-loader'
}
Copy the code
1.55. Package other resources
// Package other resources (other than HTML/JS/CSS resources)
{
// Exclude CSS /js/ HTML resources
exclude: /\.(css|js|html|less)$/,
loader: 'file-loader'.options: {
name: '[hash:10].[ext]'}}Copy the code
1.56. Devserver automation
const { resolve } = require("path");
module.export = {
entry: ' '.output: {},...// Install NPM webpack-dev-server-g
// devServer: automatic compilation, automatic open browser, automatic refresh browser
// Features: only packages are compiled in memory, with no output
// Start devServer directive: NPX webpack-dev-server
devServer: {
// Project path
contentBase: resolve(__dirname, 'build'),
// Start gzip compression
compress: true./ / the port number
port: 3000.// Automatically open the browser
open: true}}Copy the code
1.6. Basic configuration of webpack production environment
1.61. Extract CSS into separate files
NPM install --save-dev mini-css-extract-plugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module: {
rules: [{test: /\.css$/,
use: [
// Create a style tag and place the style in
// 'style-loader',
// This loader replaces style-loader. Function: Extract CSS from JS into a separate file
MiniCssExtractPlugin.loader,
// Integrate CSS files into js files
'css-loader',]}]},plugins: [
new MiniCssExtractPlugin({
// Rename the output CSS file
filename: 'css/built.css'})].mode: 'development'
Copy the code
1.62. Compatibility of the CSS
// install NPM install --save-dev mini-css-extract-plugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// Set the Node.js environment variable to determine the environment in which browserList is used
process.env.NODE_ENV = development
module: {
rules: [{test: /\.css$/,
use: [
// Create a style tag and place the style in
// 'style-loader',
// This loader replaces style-loader. Function: Extract CSS from JS into a separate file
MiniCssExtractPlugin.loader,
// Integrate CSS files into js files
'css-loader'./* CSS compatibility: postcss --> postcss-loader postCSs-preset -env Configure CSS compatibility style browserList in package.json: { "development": [" Last 1 Chrome version", "last 1 Firefox version", "Last 1 Safari version"], "production" : [">0.2 ", "not dead", "not op_mini all"]} */
{
loader: 'postcss-loader'.options: {
ident:'postcss'.plugins: () = > [
require('postcss-preset-env')()]}}]}]},plugins: [
new MiniCssExtractPlugin({
// Rename the output CSS file
filename: 'css/built.css'})].mode: 'development'
Copy the code
1.63. Compress CSS
NPM install --save-dev optimize- CSS-assets-webpack-plugin
const optimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
plugins: [
new optimizeCssAssetsWebpackPlugin()
],
Copy the code
1.64. js syntax check esLint
/* install: NPM install --save-dev eslint-loader eslint eslint-config-airbnb-base eslint-plugin-import EslintConfig: {"extends": {"extends": {"eslintConfig": {"eslintConfig": {"eslintConfig": {"eslintConfig": {"eslintConfig": {"eslintConfig": { "airbnb-base", "env": { "browser": true } } airbnb --> eslint-config-airbnb-base eslint-plugin-import eslint */
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'.options: {
// Automatically fixes esLint errors
fix: true}}Copy the code
1.65. js compatibility processing
/* npm install --save-dev babel-loader @babel/core @babel/preset-env @babel/polyfill core-js */
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'.options: { // Default: tell Babel what compatibility processing to do
presets: [['@babel/preset-env',
{
// Load as needed
useBuiltIns: 'usage'.// Specify the core-js version
corejs: {
version: 3
},
// Specify which browser version is compatible
targets: {
chrome: '60'.firefox: '60'.ie: '9'.safari: '10'.edge: '17'}}]]}}Copy the code
1.66. Js compressed
// The production environment automatically compresses the JS code
mode: 'production'
Copy the code
1.67 HTML compression
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'.// Compress the HTML code
minify: {
// Remove whitespace
collapseWhitespace: true.// Remove comments
removeComments: true}})].Copy the code
WebPack optimization configuration
2.1. HMR
HMR: Hot Module replacement Hot replacement
What it does: When a module changes, it only repackages the module, greatly improving the build speed
devServer: {
contentBase: resolve(__dirname, 'build'),
compress: true.port: 3000.open: true.// Enable HMR
// When the WebPack configuration is changed, the webpack service must be restarted for the new configuration to take effect
hot: true
}
Copy the code
2.2. The source – the map
A technique that provides source code to post-build code mapping (if post-build code fails, source code errors can be traced through the mapping)
devtool: 'the inline - source - the map | hidden - source - the map | eval - source - the map | nosources - source - the map | being - the source - the map | being - the module - the source - the map' development environment Eval-source-map Production environment source-mapCopy the code
2.3. oneOf
Only one loader will match
// The following loader will only match one
// Note: No two configurations can handle the same type of file
oneOf: [{test: /\.css$/,
use: [...commonCssLoader]
},
{
test: /\.less$/,
use: [...commonCssLoader, 'less-loader']},Copy the code
2.4. The cache
// Enable the Babel cache
// On the second build, the previous cache is read
cacheDirectory: true
Copy the code
2.5. The tree shaking
Get rid of useless code
- Prerequisites: 1. ES6 modularization must be used. 2
- Effect: Reduces code size
2.6. Code of the split
The code segment
/ / a single entrance
// entry: './src/js/index.js',
entry: {
// Multiple entries: There is one entry, and the final output has a bundle
index: './src/js/index.js'.test: './src/js/test.js' },
output: {
// [name] : Indicates the name of the file
filename: 'js/[name].[contenthash:10].js'.path: resolve(__dirname, 'build')},/* 1. The node_modules code can be packaged as a separate chunk of the final output 2. Automatic analysis of multi-entry chunks, whether there are public files. If so, it will be packaged into a single chunk */
optimization: {
splitChunks: {
chunks: 'all'}},Copy the code
2.7. Lazy loading and prefetch
2.8. PWA
Progressive Web development applications (offline access)
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
plugin: [
new WorkboxWebpackPlugin.GenerateSW({
/* 1. Help serviceworker start quickly 2. Delete the old Serviceworker. 3. Generate a Serviceworker configuration file ~ */
clientsClaim: true.skipWaiting: true})]Copy the code
2.9. Multi-process packaging
// npm install --save-dev thread-loader
{
test: /\.js$/,
exclude: /node_modules/,
use: [
loader: 'thread-loader'.options: {
workers: 2 // Process 2}}]Copy the code
2.10. externals
externals: {
// Refuse to package jQuery
// Ignore the library name -- NPM package name
jquery: 'jQuery'
}
Copy the code
2.11. The DLL
Package some libraries (third-party libraries: jquery, React, vue) separately
Detailed configuration of Webpack
3.1. The resolve
Configuring a Path Alias
resolve: {
// Configure the path alias of the resolution module: advantage short path Fault path is not displayed
alias: {
$css: resolve(__dirname, 'src/css')},// Omit the file path suffix
extensions: ['.js'.'.json'.'.jsx'.'.css'].// Tells Webpack which directory to look for
modules: [resolve(__dirname, '.. /.. /node_modules'),'node_modules']}Copy the code
3.2. optimization
module.exports = {
/ /...
optimization: {
splitChunks: {
chunks: 'async'.minSize: 20000.minRemainingSize: 0.minChunks: 1.maxAsyncRequests: 30.maxInitialRequests: 30.enforceSizeThreshold: 50000.cacheGroups: {
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10.reuseExistingChunk: true,},default: {
minChunks: 2.priority: -20.reuseExistingChunk: true,},},},},};/ * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * /
optimization: {
splitChunks: {
chunks: 'all'
// The default value is not ~
},
// Package the hash of the current module into a single file runtime
// Resolve: Modifying file A causes file B's contenthash to change
runtimeChunk: {
name: entrypoint= > `runtime-${entrypoint.name}`
},
minimizer: [
// Configure the compression scheme for the production environment: JS and CSS
new TerserWebpackPlugin({
// Enable caching
cache: true.// Enable multi-process packaging
parallel: true./ / start the source - the map
sourceMap: true}})]Copy the code
Four.WebPack5
This release focuses on the following:
- Improve build performance with persistent caching.
- Use better algorithms and defaults to improve long-term caching.
- Improved bundle size with better tree shaking and code generation.
- Clean up weird internal constructs while implementing functionality in V4 without introducing any major changes.
- Prepare for future functionality by introducing significant changes that will allow us to use V5 for as long as possible.
4.1. Chunk and module ID
New algorithms for long-term caching have been added. These are enabled by default in production mode.
chunkIds: "deterministic", moduleIds: "deterministic", mangleExports: "deterministic"
4.2. The Chunk ID
In development mode, the new named code block ID algorithm enabled by default provides human-readable names for modules (and file names). The module ID is determined by its path, relative to context. The block ID is determined by the content of the block.
So you no longer need to use import(/* webpackChunkName: “name” */ “module”) for debugging. But if you want to control filenames in your production environment, it makes sense.
You can use chunkIds in production: “named” in production, but make sure you don’t accidentally expose sensitive information about the module name.
Migration: If you don’t like changing file names during development, you can use the old digital mode via chunkIds: “Natural”.
4.3. The Tree Shaking
- Webpack can now handle tree shaking for nested modules
// inner.js
export const a = 1;
export const b = 2;
// module.js
import * as inner from './inner';
export { inner };
// user.js
import * as module from './module';
console.log(module.inner.a);
Copy the code
In a production environment, the b exposed by the inner module is removed
- Webpack is now capable of multiple module previous relationships
import { something } from './something';
function usingSomething() {
return something;
}
export function test() {
return usingSomething();
}
Copy the code
When “sideEffects”: false is set, if the test method is not used, not only test will be removed, but also “./something” will be removed.
- Webpack can now handle tree shaking for Commonjs
4.4. The Output
Webpack 4 can only output ES5 code by default
Webpack 5 starts with a new property output.ecmaVersion, which generates ES5 and ES6 / ES2015 code.
Such as: the output ecmaVersion: 2015
4.5. SplitChunk
// webpack4
minSize: 30000;
Copy the code
// webpack5
minSize: {
javascript: 30000.style: 50000,}Copy the code
4.6. Caching
// Configure the cache
cache: {
// Disk storage
type: "filesystem".buildDependencies: {
// The cache is invalid when the configuration is changed
config: [__filename]
}
}
Copy the code
The cache is stored in node_modules/.cache/webpack
4.7. Monitor output files
Previously, WebPack always exported all files on the first build, but only modified files were updated when monitoring a rebuild.
This update will find the output file on the first build to see if it has changed, so it can decide whether to output the entire file.
4.8. The default value
entry: "./src/index.js
output.path: path.resolve(__dirname, "dist")
output.filename: "[name].js"
4.9. More content
Github.com/webpack/cha…