webpack
Static Module Bundler
Target: WebPack itself is a third-party module package for Node that packages code
- Merge files of the same type
- The compressed file
- Remove the comments
- Syntax degradation (Demotes a higher version of a syntax to a lower version, compatible with all browsers)
yarn
Basic operation
#Initialize the
yarn init -y
#The installationYarn add Package name Yarn add Package name --dev
#upgradeYarn upgrade package
#removeYarn remove packagesCopy the code
Basic use of Webpack
#1. Initialize the package environment
yarn init
#2. Install dependency packages
yarn add webpack webpack-cli -D
#3. Configure scripts(custom command)-- script command yarn build
scripts: {
"build": "webpack"
}
#4. Create a directory SRC
#5. Create SRC /add/add.js - define the summation function export
export const addFn = (a, b) => a + b
#6. Create a SRC /index.js import and use it
import {addFn} from './add/add'
console.log(addFn(10, 20));
#7. Run the package commandYarn Build // is equivalent to YARN Webpack#Or NPM run build
#After packaging: SRC side by side, generate the default dist directory and the packaged default main.js file
#Static folder --public/index.html
Copy the code
Entrance and exit
Goal: Tell WebPack where to start packing and output to
The default entry is./ SRC /index.js
The default exit:./dist/main.js
Create the SRC juxtaposition (the root directory), webpack.config.js
const path = require("path")
module.exports = {
entry: "./src/main.js"./ / the entry
output: {
path: path.resolve(__dirname, "dist"), // Exit path
filename: "bundle.js" // Exit the file name}}Copy the code
Using jquery
# install yarn add jquery # SRC /index.jsimport $ from 'jquery'# Introduce the packaged js file <script SRC = in public/index.html".. /dist/main.js"></script>
Copy the code
Plugin | Loader
Automatically generated HTML file | plugins
Have webPack pack generate HTML files and automatically import packaged JS
Download the plugin
yarn add html-webpack-plugin -D
Copy the code
Webpack. Config. Js configuration
// Introduce a plug-in that automatically generates HTML
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
/ /... Omit other code
plugins: [// WebPack plugin configuration
new HtmlWebpackPlugin({
template: './public/index.html' // Use this as a base to generate a packaged HTML file}})]Copy the code
The wrapped index.html automatically imports the wrapped JS file
Handle the CSS file | loader
Reason: WebPack only recognizes JS files and JSON files by default
Target: a loaders loader that allows WebPack to handle other types of files, packaged into JS
File location: SRC/CSS /xxx.css
Install dependencies
yarn add style-loader css-loader -D
Copy the code
Webpack. Config. Js configuration
module.exports = {
/ /... Other code
module: {
rules: [ // Loader rules
{
test: /\.css$/.// Matches all CSS files
// use array to run from right to left
// Use csS-loader to enable WebPack to recognize the contents of CSS files and package them
// Use style-loader to insert the CSS into the DOM
use: [ "style-loader"."css-loader"}]}}Copy the code
New SRC/CSS /index.css – Remove the li default style
ul, li{
list-style: none;
}
Copy the code
Import SRC /index.js (because this is the entry and needs to generate the relationship before it is found and packed by WebPack)
import "./css/index.css"
Copy the code
With less paper | loader
Goal: Less-loader lets Webpack process less files and the less module translate less code
File location: SRC /less/index.less
Downloading dependency packages
yarn add less less-loader -D
Copy the code
Webpack. Config. Js configuration
module: {
rules: [ // Loader rules
/ /... Omit the other
{
test: /\.less$/.// Use less loader, let Webpack process less files, also use less to translate less code into CSS content
use: [ "style-loader"."css-loader".'less-loader']]}}Copy the code
SRC /less/index.less – Set the li font size to 24px
@size:24px;
ul, li{
font-size: @size
}
Copy the code
The introduction of the SRC/index. In js
import "./less/index.less"
Copy the code
Handle image files | loader
Target: asset module (new in webpack5)
File location: you can put it anywhere and call it whatever name you like (SRC /assets/)
Webpack. Config. Js configuration
webpack5
Configure type directly
Note:
- If type is set to
asset
- Less than 8kb, the image will be converted
base64
string - Larger than 8KB, the file is automatically named and output to dist
- Less than 8kb, the image will be converted
{
test: /\.(png|jpg|gif|jpeg)$/i,
type: 'asset'// Match the file above and WebPack will package it as a static resource
}
Copy the code
webpack4
And before, configure in use
- Download the dependency packages first
yarn add url-loader file-loader -D
{
test: /\.(png|jpg|gif|jpeg)$/i,
use: [
{
loader: 'url-loader'.// Match file, try to package base64 string into JS
// configure limit, no transfer, file-loader copy, random name, output file if the limit exceeds 8k
options: {
limit: 8 * 1024,},},],}Copy the code
Less in CSS /less/index.less – Use small images as background images (< 8KB)
- SRC is a base64 string format
body{
background: url(.. /assets/logo_small.png) no-repeat center; }Copy the code
In SRC /main.js – insert the large image into the created img tag, add the body to display (> 8KB)
- SRC is the same address
// Import image - use
import imgUrl from './assets/1.gif'
const theImg = document.createElement("img")
theImg.src = imgUrl
document.body.appendChild(theImg)
Copy the code
Advantages and disadvantages of webpack loading files
The image is converted to a Base64 string
- The advantage is that the browser doesn’t have to make a request, it can just read it
- The downside is if the picture is too big, turn it
base64
This will increase the size of the image by about 30%
Process font files | loader
Goal: With asset Module technology, asset/ Resource is exported directly to the dist directory
File location: SRC /assets/ – In the font library fonts folder
Webpackage 5 uses this configuration
{ // Webpack5 does not recognize these files internally by default, so they can be exported as static resources
test: /\.(eot|svg|ttf|woff|woff2)$/,
type: 'asset/resource'.generator: {
filename: 'font/[name].[hash:6][ext]'}}Copy the code
Webpack4 and before used the following configuration
{ // Handle font icon parsing
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: 'url-loader'.options: {
limit: 2 * 1024.// Configure the output file name
name: '[name].[ext]'.// Configure the output file directory
outputPath: "fonts/"}}}]Copy the code
Introduce iconfont. CSS in SRC /index.js
// Import the font icon file
import './assets/fonts/iconfont.css'
Copy the code
Use font icon styles in public/index.html
<i class="iconfont icon-weixin"></i>
Copy the code
Handle higher version JS syntax | loader
Goal: Get Webpack to degrade and package older VERSIONS of JS code
Reason: WebPack only has the modular compatibility handle Import Export built in by default
Babel is compatible with advanced JS syntax
Solution: Let Webpack cooperate with babel-loader to do js syntax processing
The installation package
yarn add -D babel-loader @babel/core @babel/preset-env
Copy the code
Configuration rules
module: {
rules: [{test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader'.options: {
presets: ['@babel/preset-env'] // Default: transcoding rules (with bable development environment originally preset)}}}]}Copy the code
Use advanced JS syntax in SRC /index.js
// Advanced syntax
const fn = () = > {
console.log("Hello Babel");
}
console.log(fn) // It must be called here, otherwise WebPack will not compile the unused code
// Without Babel integration, the as-is is packaged directly into lib/bundle.js
// When there is Babel integration, it is translated into normal functions and packaged into lib/bundle.js
Copy the code
WEBPACK development server
Reasons why packing takes time:
- Build dependencies
- Disk reads the corresponding file to the memory, can be loaded
- Use the corresponding Loader for processing
- Output the processed content to the specified directory on the disk
Solve a problem:
-
Automatic monitoring project source code (according to entry file)
-
As soon as changes are detected in the source code, the project is automatically compiled and the production results are automatically saved to the Dist folder
-
The compiled results are cached in server memory
-
Record the hash value of each file, and recompile only the modified files if any of them change
-
The browser can directly access the development server, which reads from the Dist directory and responds to the browser
Webpack-dev-server automatically refreshes
Goal: Start a local service that updates the modified code in real time, packages the changed code into memory, and then provides port and web access directly
Download package
yarn add webpack-dev-server -D
Copy the code
Configure custom commands in package.json
scripts: {
"build": "webpack"."serve": "webpack serve"
}
Copy the code
Run the command – start the Webpack development server
Yarn serve # or NPM run serveCopy the code
conclusion
1. What is Webpack
Webpack is a tool to package modular javascript, in Webpack all files are modules, through loader to convert files, through plugin to inject hooks, and finally output files composed of multiple modules, Webpack focuses on building modular projects
2. What are the advantages of Webpack?
- Focus on dealing with modular projects, can do out of the box, one step in place
- Plugin extension, complete and easy to use yet flexible
- With the Loaders extension, you can have WebPack parse and pack all types of files
- The region is large and active, often introducing new features that keep up with The Times, and can find existing open source extensions for most scenarios
3. What is the webpack build process? The process from reading configuration to output file is as complete as possible
The running flow of Webpack is a sequential process, from start to finish:
1. Initialization parameters: Read and merge parameters from the configuration file to obtain the final parameters. 2. Start compiling: initialize the Compiler object using the parameters obtained in the previous step, load all configured plug-ins, and start compiling. 3. Determine the 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 are processed in this step 5. Complete module compilation: After using Loader to translate all modules in Step 4, obtain the final content of each module after translation and the dependencies between them 6. Output resources: assemble chunks containing multiple modules one by one according to the dependency between the entry and modules, and then 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.Copy the code
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
4. Talk about Webpack’s hot update principle
Hot updates to Webpack are also known as Hot Module Replacement, or HMR. This mechanism allows you to replace the old module with the new one without refreshing the browser.
The core of HMR is that the client pulls the updated file from the server, namely chunk diff (the part of chunk that needs to be updated). In fact, WDS maintains a Websocket between the browser and WDS. When the local resource changes, WDS pushes updates to the browser. With the build-time hash, let the client compare to the last resource. The client compares the difference and makes an Ajax request to WDS to get the change (file list, hash), which can then be used to make jSONP requests to WDS to get incremental updates of the chunk.
What happens after you get the incremental update? Which states should be preserved? What needs updating?) This is accomplished by the HotModulePlugin, which provides apis for developers to handle their own scenarios, such as react-hot-loader and Vue-Loader, using these apis to implement HMR.
5. How is Webpack different from Grunt and gulp?
1) The difference between the three
Grunt and Gulp were popular in the early days. Webpack is relatively mainstream now, but gulp is still used for some lightweight tasks, such as packaging CSS files separately.
Grunt and gulp are based on tasks and streams (tasks, streams). Similar to jQuery, find a file (or a class of files) and do a series of chain operations on it to update the data on the stream. The chain operations constitute a single task, and multiple tasks constitute the entire Web build process.
Webpack is portal based. Webpack will automatically recursively parse all the resource files that need to be loaded by the entry, then use different loaders to process different files, and use Plugin to extend WebPack functionality.
2) From the construction idea
Gulp and Grunt require developers to divide the whole front-end construction process into multiple tasks and properly control the call relationship of all tasks. Webpack requires developers to find the entry point and figure out what Loader to use for different resources and how to parse and process them
3) For knowledge background
Gulp is more like a back end developer, you need to know the whole process very well. Webpack is more like a front end developer
6. What are the common loaders? What problems do they solve?
1. File-loader: Outputs files to a folder and references the output file with a relative URL in the code
2, url-loader: similar to file-loader, but can base64 file content into the code in the case of small files
Source-map-loader: Loads additional source map files to facilitate breakpoint debugging
4. Image-loader: loads and compresses image files
5. Babel-loader: convert ES6 to ES5
6. Css-loader: loads the CSS and supports features such as modularization, compression, and file import
7. Style-loader: Inject CSS code into JavaScript and load CSS via DOM manipulation.
8. Eslint-loader: Checks JavaScript code with ESLint
7. Difference between Loader and Plugin?
1) Different functions
Loader is a Loader. Webpack treats all files as modules, but Webpack natively only parses JS files, and if you want to package other files, you use loader. So what Loader does is give WebPack the ability to load and parse non-javascript files.
A Plugin is a Plugin. Plugin can extend the functionality of WebPack to make it more flexible. A number of events are broadcast during the life cycle of a Webpack run, and the Plugin can listen for these events and change the output when appropriate through the API provided by Webpack.
2) Different usage
Loader is configured in module.rules, which means that it exists as a parsing rule for modules. The type is array, each item is an Object, which describes the type of file (test), what to use (loader), and the parameters (options) to use.
Plugins are configured separately in plugins. Each item is an instance of plugin, and the parameters are passed in through the constructor.