1. Function
webpack is a static module packaging tool for modern JavaScript applications, packaging and compiling various types of resources into the most basic html, js, css, img, etc.
2. Installation
create npm project
npm init -y
Install webpack and scaffolding
npm install webpack webpack-cli --save-dev
3、helloword
original directory
index.html <script src="./src/index.js"></script>
src/index.js
webpack directory
1. src/index.js imports external modules
console.log("项目入口");
import { createButton } from "./utils/createbutton";
createButton("首页按钮",()=>{
console.log("首页按钮点击了");
})
utils/createButton.js
export function createButton(text, clickCallBack) {
let button = document.createElement("button");
button.innerText = text;
button.onclick = clickCallBack;
document.body.appendChild(button);
}
2. dist/index.html
<script src="./main.js"></script>
3. webpack operation
npx webpack
npx can be used for local project installation instructions and tools
will compile and generate dist in the same level directory as package.json The folder stores the compiled main.js
3. Configuration file
package.json same level directory new webpack.config.js
basic configuration
entry: "./src/index.js", // 指明打包开始文件
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"), //指明打包成果文件目录
clean: true, //清理dist下无用的文件夹
},
Parsing path resolve
configuration
resolve:{
alias:{
"@":path.resolve(__dirname, "src")
}
}
import
import { createButton } from "@/utils/createbutton";
npm custom command
npm run build
npm webpack
4. Resource loading
By default, webpack can only load js and json resources. Other resource types (img/css/vue) need to install the loader loader
css
src/assets/css/main.css
*{
margin: 0;
padding: 0;
box-sizing: border-box;
color: red;
}
import import "@/assets/css/main.css"
Error description
You may need an appropriate loader to handle this file type You may need an appropriate loader to handle this file type
Install npm install --save-dev style-loader css-loader
write rules
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
Chains are executed in reverse order. The first loader passes its result (transformed resource) to the next loader
image
src/assets/img/smallyellow.gif
导入
import smallyellow from "@/assets/img/smallyellow.gif"
Error description
You may need an appropriate loader to handle this file type You may need an appropriate loader to handle this file type
In webpack 5, you can use the built-in Asset Modules
write rules
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
load
let img = document.createElement("img");
img.src = smallyellow;
document.body.appendChild(img);
let div = document.createElement("div");
div.style.width = "400px";
div.style.height = "227px";
div.style.backgroundImage = `url(${smallyellow})`;
document.body.appendChild(div);
load font
First find the font you want to use in the Ali icon library
src/assets/font/iconfont.css
src/assets/font/iconfont.ttf
import these two files
In webpack 5, you can use the built-in Asset Modules
load
let cat = document.createElement("span");
cat.innerText="分类";
cat.classList.add("iconfont", "icon-ico-category")
document.body.appendChild(cat);
Download Data
json supports
csv by default npm install --save-dev csv-loader
configuration
{
test: /\.(csv|tsv)$/i,
use: ['csv-loader'],
},
xml npm install --save-dev xml-loader
configuration
{
test: /\.xml$/i,
use: ['xml-loader'],
},
less
src/assets/css/header.less
.header{
.nav{
width: 80%;
margin: 0 auto;
}
}
Import
import "@/css/header.less"
install
npm install less less-loader --save-dev
write rules
{
test: /\.less$/i,
use: [
// compiles Less to CSS
'style-loader',
'css-loader',
'less-loader',
],
},
5. Plug-ins
HtmlWebpackPlugin
html5 automatically generates and imports the bundle package
to install
npm install --save-dev html-webpack-plugin
configuration
const HtmlWebpackPlugin = require('html-webpack-plugin');
plugins: [new HtmlWebpackPlugin()],
MiniCssExtractPlugin
Strip css from js to reduce js file size
Install
npm install --save-dev mini-css-extract-plugin
configuration
plugins: [new MiniCssExtractPlugin()],
use: [MiniCssExtractPlugin.loader, "css-loader"],
CssMinimizerWebpackPlugin
Compress css and
install
npm install css-minimizer-webpack-plugin --save-dev
configuration
optimization: {
minimizer: [
new CssMinimizerPlugin(),
],
},
TerserWebpackPlugin
webpack5 comes with no need to install and configure html compression
const TerserPlugin = require("terser-webpack-plugin");
optimizer configuration
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
6. Code splitting
Split the js file into multiple to load on demand
Multiple js are packaged at the same time
New /src/components/header.js
console.log("header入口");
index.js import
import "@/components/header.js"
Multiple entry and exit
Configure multiple entry files
entry:{
index:"@/index.js",
header:"@/components/header.js"
},
Each entry file will be automatically imported into index.html.
In index.js, there is no need
to configure multiple export files in header.js.
output:{
filename:"[name].bundle.js",
path:path.resolve(__dirname, 'dist'),
clean:true
},
Duplicate import
Modify header.js
console.log("header入口");
import { createButton } from "@/utils/createbutton";
createButton("header按钮",()=>{
console.log("点击了header按钮");
})
At this time, the tool module createButton is packaged into index.bundle.js and header.bundle.js at the same time.
The solution uses
createButton as a separate module
. header.js and index.js rely on createButton
to reconfigure the entry file
entry:{
index:{
import:"@/index.js",
dependOn:["createbutton"]
},
header:{
import:"@/components/header.js",
dependOn:["createbutton"]
},
createbutton:{
import:"@/utils/createbutton.js"
}
},
dynamic import
Remove the entry configuration of header.js
entry:{
index:{
import:"@/index.js",
dependOn:["createbutton"]
},
// header:{
// import:"@/components/header.js",
// dependOn:["createbutton"]
// },
createbutton:{
import:"@/utils/createbutton.js"
}
Create a header when the home button is clicked
import(/* webpackChunkName:"header" */"@/components/header.js").then(()=>{
console.log("header导入完毕");
})
bundle analysis
Analyze output to check where modules end up in
webpack-chart
https://alexkuz.github.io/webpack-chart/
create generate profile directive
"profile": "webpack --profile --json > stats.json"
npm run profile
opens stats.json with page
7. Development environment
Development environment
mode: "development"
source map
code mapping
devtool: 'inline-source-map',
Development Tools
webpack-dev-server
npm install --save-dev webpack-dev-server
devDerver
devServer:{
open:true,
host:"192.168.0.10",
port:9090
}
Well, that’s all about the basic usage of webpack, I hope it can be helpful to you, thank you for being so good-looking and seeing the end, let’s have a one-click triple link~~~