Get to know Webpack
Webpack address: www.webpackjs.com/
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.
Bundler: WebPack helps you package, so it’s a packaging tool
Static: The reason for this statement is that we can eventually package the code as the ultimate static resource (deployed to a static server);
③ Modular Module: Webpack default support for a variety of modular development, ES Module, CommonJS, AMD, etc.
As we have said, it is because of the various problems faced by modern front-end development that the emergence and development of Webpack is spawned.
1, install,
Then install WebPack locally, followed by WebPack-CLI (this tool is used to run Webpack on the command line)
# global install
npm install webpack webpack-cli -g
# Partial installation
npm install webpack webpack-cli -D
Copy the code
2, use,
1) Create folder (Demo)
2) Create SRC and index.html in the folder
Note: the js file must be SRC (because at this time, you have not configured the entry file name, go to the default), so it will report an error
The default is SCR – >index.js
3) Files in SCR
Create a js folder to store CommonJS exports and ES Module exports
CommonJS export:
function fun(){
return "Price: 99.99"
}
module.exports = {
fun
}
Copy the code
ES Module export
export function add(num1, num2) {
return num1 * num2
}
Copy the code
Create an imported js file in SCR (the filename of this js file must be index.js)
import { add } from "./js/es-module";
const { fun } = require("./js/common");
console.log(add(10.10));
console.log(fun());
Copy the code
4) Run in the terminal of demo folder, and generate a dist file with main.js in the following directory after running
webpack
Copy the code
5) Add main.js to index.html, and the browser will recognize it
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<! This can also be written as the introduction of modules, so there is no need for webpack, but in this case, it needs to create a service, and it can only recognize the ES Module, / SRC /index.js" type="module"></script> -->
<script src="./dist/main.js"></script>
Copy the code
Note: Global WebPack is rarely used in real development.
3. Create a local Webpack
1) In the project directory:
npm init
# This way, it can help you generate all the information
npm init -y
Copy the code
Note: At this time, he will prompt you to fill in some information.
2) Download the WebPack dependency
npm install webpack webpack-cli -D
Copy the code
It records the version information, and the next time a dependency download is made, it will go directly to the file and make the corresponding download (that is, cache).
3) Partial packaging
npx webpack
Copy the code
Note: The packing entry and exit can be specified by writing below
NPX webpack --entry Relative path of the entry file --output-path Relative path of the exit fileCopy the code
4) When using Webpack packaging in your project, you don’t need to use 3
Create scripts in package.json and execute the script packaging
At this point, you just execute NPM run build
2. Webpack configuration file
Note: The configuration file is usually called webpack.config.js
1, specify the entrance and exit of packaging
build.js
const path = require("path");
module.exports = {
/ / the entry
entry: "./src/main.js".output: {
/** * Export file * is usually written to the absolute path, but you can use Node's path method * __dirname to get the current file location, and then write the relative path (for the file exit location) */
path: path.resolve(__dirname,"./dist"),
// Exit the file name
filename:"bundle.js"}}Copy the code
2, change the packaged configuration file name, not called webpack.config.js
1) Make changes in package.json
{
"name": "webpack-demo"."version": "1.0.0"."main": "index.js"."scripts": {
"build": "webpack --config build.js"
},
"author": ""."license": "ISC"."devDependencies": {
"webpack": "^ 5.52.0"."webpack-cli": "^ 4.8.0"
},
"dependencies": {},
"keywords": []."description": ""
}
Copy the code
You are not advised to change the configuration file name.
Webpack packs CSS resources
1. Webpack dependency graph
1) The JS files you need to package should be imported into the entry js file first
2) Create js folder under SRC
element.js
const div = document.createElement("div");
div.className = "box";
div.innerText = "Hello!
document.body.appendChild(div);
Copy the code
3) Import (i.e. index.js) in the entry file
import "./js/element"
Copy the code
4) Package it up and introduce it in index. HTML
2. Package the CSS file
CSS also introduces import files, using import, import methods, there are two ways (import location is usually used in the use).
Note: When Webopack compiles CSS, you need to download the webPack compiler dependency, otherwise it will report the following error:
1) Download dependencies
# css-loader is only responsible for parsing. CSS files, it does not insert parsed CSS into the page
npm install css-loader -D
Render the style to the page
npm install style-loader -D
Copy the code
2) Use inline (this method is not used very often)
Note: use! The partition still follows from right to left.
import "style-loader! css-loader! Relative path of CSS file"
Copy the code
3) Configuration method
Configuration information in webpack.config.js:
Module. rules allows us to configure multiple loaders (because we will continue to use other loaders to load other files).
(2) This method can better represent the loader configuration, but also convenient for later maintenance, but also let you have a global overview of each loader;
[Rule] [Rule] [Rule] [Rule] [Rule] [Rule] [Rule]
A and test are regular expressions corresponding to files to be matched
B, loader (c), loader (c), loader (d), loader (d), loader (d), loader (d), loader (d), loader (d), loader (d), loader (d
C, use:[Array] This Array contains all the loaders you need, because sometimes a loader cannot complete the required,
Also, the Array is made up of objects, because you sometimes need to pass parameters to it. The parameters of this object are as follows:
Loader: There must be a loader property with the corresponding value as a string;
Options: Optional properties. The value is a string or object. The value is passed to the loader.
webpack.config.js
const path = require("path");
module.exports = {
// entry (here the default is index.js)
entry: "./src/main.js".output: {
/** * Export file * is usually written to the absolute path, but you can use Node's path method * __dirname to get the current file location, and then write the relative path (for the file exit location) */
path: path.resolve(__dirname, "./dist"),
// Exit filename (default main.js)
filename: "main.js"
},
//
module: {
// Multiple loaders can be set
rules: [{// This is a regular expression for matching
test: /\.css$/.// Use that loader
// Loader syntax sugar mode 1
// loader: "css-loader"
/** * Method 2 * use loads the loader from bottom to top */
use: [
{ loader: "style-loader" }, // use (style-loader)
// "csS-loader
{ loader: "css-loader" } // 1, webPack can load CSS}]}}Copy the code
Note: The following error will be reported when the loader loading sequence is incorrect:
4. Handle less files
1, download
# download less
npm install less --save -d
# less CSSNPX Lessc less Relative path of the file less Relative path of the CSSInstall less loader so that webpack can handle less
npm install less-loader -d
Copy the code
2. Introduce less in packaged JS files
3. Configure it in webpacjk.config.js
const path = require("path");
module.exports = {
// entry (here the default is index.js)
entry: "./src/main.js".output: {
/** * Export file * is usually written to the absolute path, but you can use Node's path method * __dirname to get the current file location, and then write the relative path (for the file exit location) */
path: path.resolve(__dirname, "./dist"),
// Exit filename (default main.js)
filename: "main.js"
},
//
module: {
// Multiple loaders can be set
rules: [
/* CSS processing */
{
// This is a regular expression for matching
test: /\.css$/.// /\.(less|css)$/
// Use that loader
// Loader syntax sugar mode 1
// loader: "css-loader"
/** * Method 2 * use loads the loader from bottom to top */
use: [
{ loader: "style-loader" }, // use (style-loader)
// "csS-loader
{ loader: "css-loader" } // 1, webPack can load CSS]},/* less */
{
test: /\.less$/i.// Add I is case insensitive
use:[
// All three of the following
"style-loader"."css-loader"."less-loader"}]}}Copy the code
Note: Less and CSS can also be configured together
const path = require("path");
module.exports = {
// entry (here the default is index.js)
entry: "./src/main.js".output: {
/** * Export file * is usually written to the absolute path, but you can use Node's path method * __dirname to get the current file location, and then write the relative path (for the file exit location) */
path: path.resolve(__dirname, "./dist"),
// Exit filename (default main.js)
filename: "main.js"
},
//
module: {
// Multiple loaders can be set
rules: [{test: /\.(less|css)$/i.// To match either less or CSS
use: [
// All three of the following
"style-loader"."css-loader"."less-loader"}]}}Copy the code
Fifth, PostCSS
1. Introduction to PostCSS
1) PostCSS is a tool for converting styles through JavaScript;
2) This tool can help us to do some CSS transformation and adaptation, such as automatically adding browser prefix, CSS style reset.
2, installation,
npm install postcss postcss-cli -D
Add browser prefix automatically
npm install autoprefixer -D
Copy the code
Transform (after the transform is complete, he prefixes the CSS properties with the browser)
NPX postcss --use autoprefixer -o Relative path of the output CSS CSS Relative path of the input CSS file CSSCopy the code
3. Use plug-ins in Webpack that automatically prefix browsers
1) installation
npm install postcss-loader -D
Copy the code
2) use
const path = require("path");
module.exports = {
// entry (here the default is index.js)
entry: "./src/main.js".output: {
/** * Export file * is usually written to the absolute path, but you can use Node's path method * __dirname to get the current file location, and then write the relative path (for the file exit location) */
path: path.resolve(__dirname, "./dist"),
// Exit filename (default main.js)
filename: "main.js"
},
//
module: {
// Multiple loaders can be set
rules: [{// This is a regular expression for matching
test: /\.css$/.// Use that loader
// Loader syntax sugar mode 1
// loader: "css-loader"
/** * Method 2 * use loads the loader from bottom to top */
use: [
"style-loader".// use (style-loader)
// "csS-loader
"css-loader".// 1, webPack can load CSS
// When using postCSs-loader, you must write it as an object. You must specify which plug-ins it uses
{
loader: "postcss-loader".options: {
postcssOptions: {
// Specify the plugins you use
plugins: [// Automatically prefix the browser
require("autoprefixer"]}}}]}}Copy the code
3) Used as above, ugly display in configuration file, can be extracted (separate configuration)
① Create postcss.config.js in the project directory
module.exports = {
// Specify the plugins you use
plugins: [
// Automatically prefix the browser
require("autoprefixer")]}Copy the code
② Configuration in webpack.config.js
const path = require("path");
module.exports = {
// entry (here the default is index.js)
entry: "./src/main.js".output: {
/** * Export file * is usually written to the absolute path, but you can use Node's path method * __dirname to get the current file location, and then write the relative path (for the file exit location) */
path: path.resolve(__dirname, "./dist"),
// Exit filename (default main.js)
filename: "main.js"
},
//
module: {
// Multiple loaders can be set
rules: [{// This is a regular expression for matching
test: /\.css$/.// Use that loader
// Loader syntax sugar mode 1
// loader: "css-loader"
/** * Method 2 * use loads the loader from bottom to top */
use: [
"style-loader".// use (style-loader)
// "csS-loader
"css-loader".// 1, webPack can load CSS
Postcss-loader: postcss-loader: postcss-loader: postCSs-loader: postCSs-loader: postCSs-loader: postCSs-loader: postCSs-loader
"postcss-loader",]}]}}Copy the code
4, Use of postCSS-PRESET -env (preset environment)
Note: ① Convert some modern CSS features into CSS that most browsers know, and add the required polyfills depending on the target browser or runtime environment;
② Will automatically help us add Autoprefixer.
1) installation
npm install postcss-preset-env -D
Copy the code
2) use
module.exports = {
// Specify the plugins you use
plugins: [
// Automatically prefix the browser
require("postcss-preset-env")]}Copy the code
The contents of webpack.config.js do not change.
Vi.Asset-modules (Resource module type)
Webpack4 loader in the use of: v4.webpack.js.org/loaders/#ro…
1, the introduction
1) Asset module is a module that allows people to use asset files (fonts, ICONS, etc.) without configuring additional loaders.
Before WebPack 5, it was common to use:
1 Raw-loader imports the file as a string
② Url-loader inlines the file to the package as a data URI
③ file-loader sends the file to the output directory
2) Asset module types Replace all of these loaders by adding 4 new module types (webpack5+ and above is acceptable) :
① Asset/Resource emits a separate file and exports the URL. Previously, file-loader could be used
② asset/inline Exports the data URI of the asset (base64). Previously, url-loader could be used
The source code of the asset can be exported by using raw-loader
④ Asset automatically chooses between exporting data URIs and issuing individual files, which was previously possible using urL-Loader asset size limitation (LIMT).
2. Load images
Note: If the image is too small, change it to Base64
webpack.config.js:
module.exports = {
/* If the input/output is not defined, then it is the default to go */
module: {
rules: [
// image processing, webpack5+ is no longer needed
{
test: /\.(jpe? g|png|gif|svg)$/,
type: "asset".generator: {
/** * the extension of webpack5+ contains dots, not dots. AssetModuleFilename :'img/[name]_[hash:6][ext]') * img Filename to store * [name] original image name * _ Delimiter, optional * [hash:6] hash mode, Keep the extension of the first six * [ext] images */
filename: "img/[name]_[hash:6][ext]",},/ / write restrictions
parser: {
// Data condition
dataUrlCondition: {
// This is unit B
maxSize: 100 * 1024,}}}]}}Copy the code
3. Load fonts
webpack.config.js:
module.exports = {
/* If the input/output is not defined, then it is the default to go */
module: {
rules: [
// Handle special fonts, including Ali's vector ICONS
{
test: /\.(eot|ttf|woft2?) $/,
type: "asset/resource".generator: {
/** * the extension of webpack5+ contains dots, not dots. AssetModuleFilename :'font/[name]_[hash:8][ext]') * img Filename to store * [name] original image name * - Delimiter, optional * [hash:6] Hash mode, Keep the first six * [ext] font extensions */
filename: "font/[name]-[hash:8][ext]"}}]}}Copy the code
Seven,The plug-in (plugins)
Plug-ins are the backbone of WebPack. Webpack itself is also built on top of the same plugin system that you use in webPack configuration. Plugins are designed to do other things that loader cannot do, for example:
① Loader is used to convert specific module types;
Plugin can be used to perform a wider range of tasks, such as packaging optimization, resource management, environment variable injection, etc.
③ Plug-ins are executed in no order.
1. Use of the clean-webpack-plugin
Note: This plugin can actively delete packaged files
1) installation
npm install clean-webpack-plugin -D
Copy the code
2) Import webpack
In webpack. Config. In js:
const path = require("path");
// CleanWebpackPlugin is a class
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
output: {
path: path.resolve(__dirname, "./build"),
filename: "main.js"
},
// Plugins are the same class as modules.
plugins: [
/** * CleanWebpackPlugin will automatically read the path corresponding to the output in the context and delete ** note: this must be set to output and does not delete the default */
new CleanWebpackPlugin()
]
}
Copy the code
2,HtmlWebpackPlugin
Note: Generate the entry HTML in the package.
HTML – webpack – is the official document: www.webpackjs.com/plugins/htm…
1) installation
npm install html-webpack-plugin -D
Copy the code
2) use
Import in webpack.config.js:
const path = require("path");
// CleanWebpackPlugin is a class
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
output: {
path: path.resolve(__dirname, "./build"),
filename: "js/main.js" // Specify the js package directory
},
// Inside this is a plug-in object
plugins: [
/** * CleanWebpackPlugin will automatically read the path corresponding to the output in the context and delete ** note: this must be set to output and does not delete the default */
new CleanWebpackPlugin(),
new HtmlWebpackPlugin()
]
}
Copy the code
3) Specify the HTML packaging template
① First create an HTML file as a template
index.html
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Specify the HTML packaging template</title>
</head>
<body>
</body>
</html>
Copy the code
2. Webpack.config.js
const path = require("path");
// CleanWebpackPlugin is a class
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
/** * fill the BASE_URL with data, that is, the little icon that fills the page */
module.exports = {
output: {
path: path.resolve(__dirname, "./build"),
filename: "js/main.js" // Specify the js package directory
},
// Inside this is a plug-in object
plugins: [
/** * CleanWebpackPlugin will automatically read the path of output in context and delete */
new CleanWebpackPlugin(),
// Specify the HTML packaging template
new HtmlWebpackPlugin({
// This is tiele
title: "Specify HTML packaging template".// Pass the specified template path
template: "./index.html",}})]Copy the code
3. Introduction to DefinePlugin
Note: ① DefinePlugin is used together with HtmlWebpackPlugin;
(1) If the BASE_URL constant is not set, the following error will be reported:
In this case, use the DefinePlugin.
(3) document: www.webpackjs.com/plugins/def…
1) use
DefinePlugin is a plug-in built into WebPack (it doesn’t need to be installed separately).
index.html
<! DOCTYPEhtml>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
</body>
</html>
Copy the code
2) Define the variable
const path = require("path");
// CleanWebpackPlugin is a class
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
// Read the HTML template from the definition
const HtmlWebpackPlugin = require("html-webpack-plugin");
/** * Fill the BASE_URL with data, that is, the little icon that fills the page * set the constant in the template */
const { DefinePlugin } = require("webpack")
module.exports = {
output: {
path: path.resolve(__dirname, "./build"),
filename: "js/main.js" // Specify the js package directory
},
// Inside this is a plug-in object
plugins: [
/** * CleanWebpackPlugin will automatically read the path corresponding to the output in the context and delete ** note: this must be set to output and does not delete the default */
new CleanWebpackPlugin(),
// Specify the HTML packaging template
new HtmlWebpackPlugin({
// This is tiele
title: "Specify HTML packaging template".// Pass the specified template path
template: "./index.html",}).new DefinePlugin({
// To define the value, you also need to put single quotes inside the double quotes (that is, the path, and the HTML <%= BASE_URL %> value, concatenated into a full path)
BASE_URL: "'/'"}})]Copy the code
4. CopyWebpackPlugin (copy the specified file to the package file)
1) installation
npm install copy-webpack-plugin -D
Copy the code
2) use
webpack.config.js
const path = require("path");
// CleanWebpackPlugin is a class
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
// Read the HTML template from the definition
const HtmlWebpackPlugin = require("html-webpack-plugin");
// Set the constants in the template
const { DefinePlugin } = require("webpack");
const CopyWebpackPlugin = require("copy-webpack-plugin")
/** * fill the BASE_URL with data, that is, the little icon that fills the page */
module.exports = {
output: {
path: path.resolve(__dirname, "./build"),
filename: "js/main.js" // Specify the js package directory
},
/* If the input/output is not defined, then it is the default to go */
module: {
rules: [{test: /\.css$/,
use: [
"style-loader"."css-loader"."postcss-loader",]},// image processing, webpack5+ is no longer needed
{
test: /\.(jpe? g|png|gif|svg)$/,
type: "asset".generator: {
/** * the extension of webpack5+ contains dots, not dots. AssetModuleFilename :'img/[name]_[hash:6][ext]') * img Filename to store * [name] original image name * _ Delimiter, optional * [hash:6] hash mode, Keep the extension of the first six * [ext] images */
filename: "img/[name]_[hash:6][ext]",},/ / write restrictions
parser: {
// Data condition
dataUrlCondition: {
// This is unit B
maxSize: 100 * 1024,}}},// Handle special fonts, including Ali's vector ICONS
{
test: /\.(eot|ttf|woff2?) $/,
type: "asset/resource".generator: {
/** * the extension of webpack5+ contains dots, not dots. AssetModuleFilename :'font/[name]_[hash:8][ext]') * img Filename to store * [name] original image name * _ Delimiter, optional * [hash:6] hash mode, Keep the first six * [ext] font extensions */
filename: "font/[name]-[hash:8][ext]"}}},// Inside this is a plug-in object
plugins: [
/** * CleanWebpackPlugin will automatically read the path corresponding to the output in the context and delete ** note: this must be set to output and does not delete the default */
new CleanWebpackPlugin(),
// Specify the HTML packaging template
new HtmlWebpackPlugin({
// This is tiele
title: "Specify HTML packaging template".// Pass the specified template path
template: "./public/index.html",}).new DefinePlugin({
// Define the value, and enclose the single quotation mark inside the double quotation mark
BASE_URL: "'/'"
}),
// Copy the file to the package folder
new CopyWebpackPlugin({
☞ select * from: "you want to copy the contents of the folder, including subfolders ", to: // Ignore a file in the folder you want to copy./ / Ignore the file name in the folder you want to copy. [// ignore all index.html, including those in subdirectories so add ** "star/file name to ignore"]}} */
patterns: [{from: "public".to: ". /".//./ ABC creates an ABC folder in the packaged directory
// Ignore a file in the folder you want to copy
globOptions: {
// The file name you want to ignore
ignore: [
// Ignore all index. HTML, including those in subdirectories
"**/index.html"]}}]})]}Copy the code
Note: Code splitting can be done using code-splitting.
Use of Babel
Note: Babel official website: babeljs. IO /
Github.com/jamiebuilds…
1. Use the Babel command
Note: Babel itself can be used as a standalone tool (like PostCSS), not as a standalone build tool configuration such as WebPack.
1) To try using Babel on the command line, you need to install the following libraries:
@babel/core: the core code of Babel, must be installed;
@babel/cli: let’s use Babel at the command line (if we use it in webpack, we don’t need to install it)
npm install @babel/cli @babel/core -D
Copy the code
2) run
NPX Babel The file name to escape.js/ or folder (this is the relative path) --out-dir The file location after the transferOr specify the file you want to escape, and specify the name of the file generated by the escape
npx babel demo.js --out-file dist.js
Copy the code
3) But the above operation, he did not convert the file, because to convert, you need to download the corresponding plug-in (that is, to convert the function needs to install the plug-in), after downloading the plug-in run:
NPX Babel SRC --out-dir dist --plugins=@babel/plugin-transform-arrow-functionsCopy the code
4) Conversion of arrow function
① Use the arrow function to convert related plug-ins
npm install @babel/plugin-transform-arrow-functions -D
Copy the code
② Use the installed plug-in
npx babel src --out-dir dist --plugins=@babel/plugin-transform-arrow-functions
Copy the code
5) Convert const to var
(1) the installation
npm install @babel/plugin-transform-block-scoping -D
Copy the code
< span style = “max-width: 100%; clear: both;
npx babel demo.js --out-file dist.js --plugins=@babel/plugin-transform-arrow-functions,@babel/plugin-transform-block-scoping
Copy the code
6) preset
Note: Preset is too troublesome to rely on installers as above, we can use preset.
(1) the installation
npm install @babel/preset-env -D
Copy the code
(2) use
npx babel src --out-dir dist --presets=@babel/preset-env
Copy the code
Note: The difference between converting to folders and files:
Convert js from SRC to dist
npx babel src --out-dir dist --presets=@babel/preset-env
Convert demo.js to dist. Js
npx babel demo.js --out-file dist.js --presets=@babel/preset-env
Copy the code
7) Implementation phase of Babel
Graph LR (source code to write their own A) -- -- > B (parsing) B > C (conversion) C - > D (code generation) D - > E (target source)
2, Use Babel in webpack (babel-loader)
1) installation
npm install @babel/cli -D
npm install babel-loader -D
Copy the code
2) use
const path = require("path");
module.exports = {
// Set the mode
// In the development phase, the development is set
// Production Set production when ready to go live
mode: "development".// Set source-map to create js mapping files for debugging code and errors
devtool: "source-map".entry: "./src/index.js".output: {
path: path.resolve(__dirname, "./build"),
filename: "js/main.js" // Specify the js package directory
},
/* If the input/output is not defined, then it is the default to go */
module: {
rules: [{test: /\.css$/,
use: [
"style-loader"."css-loader"."postcss-loader",]},// image processing, webpack5+ is no longer needed
{
test: /\.(jpe? g|png|gif|svg)$/,
type: "asset".generator: {
/** * the extension of webpack5+ contains dots, not dots. AssetModuleFilename :'img/[name]_[hash:6][ext]') * img Filename to store * [name] original image name * _ Delimiter, optional * [hash:6] hash mode, Keep the extension of the first six * [ext] images */
filename: "img/[name]_[hash:6][ext]",},/ / write restrictions
parser: {
// Data condition
dataUrlCondition: {
// This is unit B
maxSize: 10 * 1024,}}},// Handle special fonts, including Ali's vector ICONS
{
test: /\.(eot|ttf|woff2?) $/,
type: "asset/resource".generator: {
/** * the extension of webpack5+ contains dots, not dots. AssetModuleFilename :'font/[name]_[hash:8][ext]') * img Filename to store * [name] original image name * _ Delimiter, optional * [hash:6] hash mode, Keep the first six * [ext] font extensions */
filename: "font/[name]-[hash:8][ext]"}}, {test: /\.js$/,
use: {
loader: "babel-loader".options: {
/** * This is a different plugin configuration (generally not used this way) ** To use the following two plug-ins, you need to download: * NPM install@babel/plugin-transform-arrow-functions -D
* npm install @babel/plugin-transform-block-scoping -D
plugins: [
"@babel/plugin-transform-arrow-functions",
"@babel/plugin-transform-block-scoping"
]
*/
presets: [
[" plug-in name ",{}] */
"@babel/preset-env"}}}]}}Copy the code
3) Extract the configuration of babel-loader
① Create the following files in the following directories
File babel.config.js (or.cjs,.mjs);
.babelrc.js (or.babelrc,.cjs,.mjs) files;
Choose one of these two
babel.config.js
module.exports = {
// Specify the plugins you use
plugins: [
// Automatically prefix the browser
require("postcss-preset-env")]}Copy the code
(2) webpack.config.js
Webpack automatically compiles
Note: when the file is modified, automatically compiled, do not modify the following, packaged once.
1, Webpack watch
In this mode, WebPack relies on all the files in the diagram, and if one of them is updated, the code will be recompiled.
1) How to open the Watch? Two ways:
Method 1: Add watch: true in the exported configuration.
Method 2: In the command to start webpack, add –watch logo;
2) In the command to start webpack, add the –watch logo
① Configure it in package.json
"scripts": {
"build": "webpack"."watch": "webpack --watch"
},
Copy the code
Note: it will be compiled according to webpack CLI.
(2) run:
npm run watch
Copy the code
(3) open
In the generated package file, use Live Server to open the generated index.html file.
3) Add configuration options in webpak.config.js
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { DefinePlugin } = require("webpack");
const CopyWebpackPlugin = require("copy-webpack-plugin")
module.exports = {
mode: "development".devtool: "source-map".// Turn on listening here (when using it, you can remove the configuration in package.json)
watch: true.entry: "./src/index.js".output: {
path: path.resolve(__dirname, "./build"),
filename: "js/main.js" // Specify the js package directory
},
module: {
rules: [{test: /\.css$/,
use: [
"style-loader"."css-loader"."postcss-loader",]}, {test: /\.(jpe? g|png|gif|svg)$/,
type: "asset".generator: {
filename: "img/[name]_[hash:6][ext]",},parser: {
dataUrlCondition: {
maxSize: 10 * 1024,}}}, {test: /\.(eot|ttf|woff2?) $/,
type: "asset/resource".generator: {
filename: "font/[name]-[hash:8][ext]"}}, {test: /\.js$/,
loader: "babel-loader"}},plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Specify HTML packaging template".template: "./public/index.html",}).new DefinePlugin({
BASE_URL: "'/'"
}),
new CopyWebpackPlugin({
patterns: [{from: "public".to: ". /".globOptions: {
ignore: [
"**/index.html"]}}]})]}Copy the code
Run:
The build command is configured in package.json as follows:
# "scripts": {
# "build": "webpack"
#}.
npm run build
Copy the code
2, webpack – dev – server
Note: The use of webpack-dev-server may not apply to live-server in VSC.
1) installation
npm install webpack-dev-server -D
Copy the code
2) Configure in package.json
Webpack serve can be followed by the configuration file address, written as webpack serve –config line pair path to the configuration file
"scripts": {
"build": "webpack"."serve": "webpack serve"
},
Copy the code
3) run
npm run serve
Copy the code
At this time, the generated folder is empty, it will be placed in memory.
3, devServer configuration (i.e. webpack-dev-server configuration)
1) Module hot replacement
① Webpack.config. js configuration
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { DefinePlugin } = require("webpack");
const CopyWebpackPlugin = require("copy-webpack-plugin")
module.exports = {
/** * webpack why pack * target content: web, node */
target:"web".mode: "development".devtool: "source-map".entry: "./src/index.js".output: {
path: path.resolve(__dirname, "./build"),
filename: "js/main.js" // Specify the js package directory
},
devServer: {/** * If you can't load any resources in the webPak package, you can find them in the contentBase folder specified for loading. CopyWebpackPlugin is a waste of resources during development, so use contentBase instead. So you can unlog the following CopyWebpackPlugin configuration during development, but you still need to copy it during production
contentBase: "./public"./** * module hot replacement: * module hot replacement refers to replacing, adding, and removing modules while the application is running without having to refresh the entire page ** / example: when you are using the calculator, you do not want to modify the code and the result of the calculator is also lost
hot: true,},module: {
rules: [{test: /\.css$/,
use: [
"style-loader"."css-loader"."postcss-loader",]}, {test: /\.(jpe? g|png|gif|svg)$/,
type: "asset".generator: {
filename: "img/[name]_[hash:6][ext]",},parser: {
dataUrlCondition: {
maxSize: 10 * 1024,}}}, {test: /\.(eot|ttf|woff2?) $/,
type: "asset/resource".generator: {
filename: "font/[name]-[hash:8][ext]"}}, {test: /\.js$/,
loader: "babel-loader"}},plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Specify HTML packaging template".template: "./public/index.html",}).new DefinePlugin({
BASE_URL: "'/'"
}),
// At development time, performance savings can be logged off
// new CopyWebpackPlugin({
// patterns: [
/ / {
// from: "public",
// to: "./",
// globOptions: {
// ignore: [
// "**/index.html"
/ /]
/ /}
/ /}
/ /]
// })]}Copy the code
(2) Introduce the writing method of hot replacement module
/** * If you use hot replacement for each module, at this point you cannot use the previous method ** in webpack a JS file is a module * to be replaced with the following method: */
import "./js/element"
if(module.hot){
module.hot.accept("./js/element.js".() = > {
console.log("Hot replacement of modules"); })... Similar to the above, to specify multiple modules}Copy the code
③ Implementation effect:
2) Host configuration
Localhost 0.0.0.0
A. localhost: is essentially a domain name that is normally resolved to 127.0.0.1;
127.0.0.1: Loop Back Address, which means that the packet sent by the host is directly received by itself.
C. Normal database package path:
Graph LR (application layer) -- - > B () transport layer B -- -- -- -- > > C (network layer) C D (data link layer) D - > E (physical)
D. The loopback address is directly obtained at the network layer and is not frequently accessed at the data link layer and physical layer.
E. For 127.0.0.1, hosts in the same network segment cannot be accessed using IP addresses.
F, we listen for 0.0.0.0, in the same network segment of the host, through the IP address is accessible.
② host Set the host address.
The default is localhost;
If you want access from other places, set it to 0.0.0.0.
3) port Sets the listening port. The default port is 8080
4) Compress Whether to enable Gzip for static files
Note: it does not compress HTML, and it does not matter if this is turned on or off, because it is transmitted locally.
When you set this up, every time the browser requests a resource, it will look something like this:
devServer:{
/** * Whether to enable gzip for static files * Default is false */
compress: true
},
Copy the code
4. Cross-domain Proxy
devServer: {
proxy: {
// / API is the address of the proxy
"/api": {
// Here is the server address
target: "http://localhost:8888"./** * "^/ API ": "This will be matched to the url" * ^/ API is matched to the content after/API */
pathRewrite: {
"^/api": ""
},
/** * Secure: by default, servers that forward to HTTPS are not accepted and the certificate is invalid. If you want to support this, set this parameter to false */
secure: false./** * Change source: generally true */
changeOrigin: true}}},Copy the code
5. Resolve module resolution
1) Resolve is used to set how the module is resolved:
During development we have a variety of module dependencies, either from our own code or from third-party libraries;
Resolve helps WebPack find the appropriate module code to import from each require/import statement;
Webpack uses enhanced-resolve to resolve file paths
2) Webpack can resolve three file paths:
① Absolute path
Since you already have the absolute path to the file, no further parsing is required.
② Relative path
In this case, the directory in which the resource files that use import or require reside is considered the context directory, and the relative path given in import/require is concatenated to generate the absolute path of the module.
③ Module path
Modules are retrieved from all directories specified in resolve.modules. The default is [‘node_modules’], so files are looked up from node_modules by default.
3) use
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { DefinePlugin } = require("webpack");
const CopyWebpackPlugin = require("copy-webpack-plugin")
module.exports = {
/** * webpack why pack * target content: web, node */
target: "web".mode: "development".devtool: "source-map".entry: "./src/index.js".output: {
path: path.resolve(__dirname, "./build"),
filename: "js/main.js" // Specify the js package directory
},
devServer: {
/** * If you can't load any resources in the webPak package, you can find them in the contentBase folder specified for loading. CopyWebpackPlugin is a waste of resources during development, so use contentBase instead. So you can unlog the following CopyWebpackPlugin configuration during development, but you still need to copy it during production
contentBase: "./public"./** * module hot replacement: * module hot replacement refers to replacing, adding, and removing modules while the application is running without having to refresh the entire page ** / example: when you are using the calculator, you do not want to modify the code and the result of the calculator is also lost
hot: true./ / host: "0.0.0.0",
port: 7777./** * Whether to enable gzip for static files * Default is false */
compress: true./** * cross-domain */
proxy: {
// / API is the address of the proxy
"/api": {
// Here is the server address
target: "http://localhost:8888"./** * "^/ API ": "This will be matched to the url" * ^/ API is matched to the content after/API */
pathRewrite: {
"^/api": ""
},
/** * Secure: by default, servers that forward to HTTPS are not accepted and the certificate is invalid. If you want to support this, set this parameter to false */
secure: false./** * Change source: generally true */
changeOrigin: true}}},resolve: {
/** * if it is a file: * It will automatically match the path based on what is written in the extensions folder, go to the folder to find the corresponding file * the default value in the extensions folder is: [" js ", "json", "MJS", "wasm"] * can give the following to join in the vue. Ts. JSX * /
extensions: [".js".".json".".mjs".".wasm"]./** * If it is a folder * resolves resolves by the file order specified in the resolve.mainFiles configuration option. The default value of resolve.mainFiles is ['index'] Resolve the * mainFiles extension */
mainFiles: ["index"]./** * is the configuration alias alias * "alias name ": path.resolve(__dirname," relative to configuration file path ") */
alias: {
"js": path.resolve(__dirname, "./src/js")}},module: {
rules: [{test: /\.css$/,
use: [
"style-loader"."css-loader"."postcss-loader",]}, {test: /\.(jpe? g|png|gif|svg)$/,
type: "asset".generator: {
filename: "img/[name]_[hash:6][ext]",},parser: {
dataUrlCondition: {
maxSize: 10 * 1024,}}}, {test: /\.(eot|ttf|woff2?) $/,
type: "asset/resource".generator: {
filename: "font/[name]-[hash:8][ext]"}}, {test: /\.js$/,
loader: "babel-loader"}},plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Specify HTML packaging template".template: "./public/index.html",}).new DefinePlugin({
BASE_URL: "'/'"
}),
// At development time, performance savings can be logged off
// new CopyWebpackPlugin({
// patterns: [
/ / {
// from: "public",
// to: "./",
// globOptions: {
// ignore: [
// "**/index.html"
/ /]
/ /}
/ /}
/ /]
// })]}Copy the code
All code address: www.lanzouw.com/iaDu3uba7le