1. Webpack profile
1.1 What is Webpack?
Webpack is a front-end resource builder, a static Module bundler. In webpack’s view, the front-end has many resource files (JS /json/ CSS /img/less/…). Will be treated as modules. It will carry out static analysis according to module dependencies and generate corresponding static resources (bundles).
1.2 Five core concepts of Webpack
-
Entry: The Entry indicates which file webPack starts packing as the Entry point, analyzing and building the internal dependency diagram.
-
Output: The Output indicates where the Output of resource bundles packaged by Webpack goes and how to name them.
-
Loader: Loader enables Webpack to handle non-javascript files (WebPack itself only understands Javascript).
-
Plugins: Plugins can be used to perform a wider range of tasks, from packaging optimization and compression to redefining variables in the environment.
-
Mode: Mode instructs WebPack to use the configuration of the corresponding Mode.
options describe The characteristics of development: will DefinePlugin
中process.env.NODE_ENV
Is set todevelopment
, enablingNamedChunksPlugin
和NamedModulesPlugin
.A runtime environment that allows code to be debugged locally production: will DefinePlugin
中process.env.NODE__ENV
Is set toproduction
. To enable theFlagDependencyUsagePlugin
.FlagIncludedChunksPlugin
ModuleConcatenationPlugin
.NoEmitOnErrorsPlugin
.OccurrenceOrderPlugin
.SideEffectsFlagPlugin
和TerserPlugin
.A runtime environment in which code can be optimized to live
2. Webpack initial experience:
The directory structure is as follows:
Code:
// index: entry starting file for Webpack
import data from "./test.json";
import test from "./test.css";
function add(x,y){
return x + y
}
console.log(add(1.2))
console.log("I am a json",data);
Copy the code
//test.json
{
"key": "Test JSON file packaging"
}
Copy the code
// test.css
body{
background-color: #42b983;
height: 1000px;
width: 100%;
}
Copy the code
Index.html at the root of the folder:
- here
script
I’m introducing the packaged onesmain.js
file build
A new folder for the root directory
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="./src/test.css">
</head>
<body>
<script src="./build/main.js"></script>
</body>
</html>
Copy the code
Installation and packaging operations:
Installation:
- Install globally first:
npm i webpack webpack-cli -g
- Installation in the project:
npm i webpack webpack-cli -D
Packaging:
- Development environment:
- Command:
webpack ./src/index.js -o ./build --mode=development
(-o
It means thatoutput
Output) - Function:
webpack
Ability to compile and packagejs
andjson
File, and can bees6
Convert the modular syntax of the browser to a syntax that the browser can recognize.
- Command:
- Production environment:
- Command:
webpack ./src/index.js -o ./build --mode=production
- Function: in the development configuration function on a function, compression code
- Command:
Question:
Error found in packing after importing CSS file:
Conclusion:
webpack
Can deal withjs
andjson
File, cannot be processedcss/img
And other resourcesGenerate environment
andThe development environment
willES6
Modularity compiles to browser-awaremodule
The production environment
thanThe development environment
More than aCompression js
code
3. Webpack resources:
1. Tocss
andless
Packaging:
- Create one at the root of your project
webpack.config.js
File, which is mainly used to tellwebpack
—You're going to do something
const {resolve} = require("path");
: used to concatenate absolute pathsresolve(__dirname,"build"):
__dirname
Represents theThe absolute directory path of the current file
, it isnodejs
A variable of
The module of the rules
Is used to configureloader
thetest
To match filesuse
To process matching files,use
The order of execution in the array isFrom the bottom up
- packaging
less
File when you need to pay attention to installationless
andless-loader
.less
Do not configure touse
In the array
// Tell webpack what to do
// All build tools run on the NodeJS platform and modularity defaults to commonJS syntax
const {resolve} = require("path");
module.exports = {
/ / the entry
entry:"./src/index.js"./ / export
output: {// Package the output file name
filename:"build.js".//__dirname represents the absolute directory path of the current file and is a variable of nodejs
path:resolve(__dirname,"build")},/ / loader configuration
module: {rules: [// Detailed loader configuration
{
//test -- matches a.css file ending
test:/\.css$/.// Use means which loaders are used for processing. The order of execution in the use array is from bottom to top
use:[
// Insert the style tag and js style resources into the head
"style-loader".//css-loader converts CSS files into commonJS modules and loads them into JS modules
"css-loader"] {},//test -- matches a.css file ending
test:/\.less$/.// Use means which loaders are used for processing. The order of execution in the use array is from bottom to top
use:[
// Insert the style tag and js style resources into the head
"style-loader".//css-loader converts CSS files into commonJS modules and loads them into JS modules
"css-loader"."less-loader",]}]},/ / the plugin
plugins: [// Detailed configuration of the plug-in]./ / mode
mode:"development"
}
Copy the code
For 2.html
Packaging:
The HTML is processed here using a plug-in.
npm i html-webpack-plugin -D
Copy the code
webpack.config.js
Code:
- The installation finished
html-webpack-plugin
After that, use is neededThe introduction of
theconst HtmlWebpackPlugin = require("html-webpack-plugin");
template
: Just a template, copy"./src/index.html"
File resources, and automatically import packaged output all resources (JS/CSS)
//webpack.config.js
const {resolve} = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports={
entry:"./src/index.js".output: {filename:"html.js".path:resolve(__dirname,"build")},module: {rules: []},plugins: [// Create an empty HTML by default, automatically import packaged output all resources (js/ CSS)
new HtmlWebpackPlugin({
// Copy the "./ SRC /index.html" file resources and automatically import the package output all resources (js/ CSS)
template:"./src/index.html"})].mode:"development"
}
Copy the code
Packing results:
You’ll notice that an extra index.html file is generated under the build folder
3. Packaging of image resources:
Folder structure:
├ ─ webpack. Config. Js ├ ─ SRC | ├ ─ BBB. Jpeg | ├ ─ index. The HTML | ├ ─ index. The js | └ index. The lessCopy the code
webpack.config.js
:
There is no need to elaborate on the index.js and other contents of the entry, similar to the above. Let’s take a quick look at webpack.config.js configuration:
- Used here
url-loader
I’m going to do something with the image, buturl-loader
Depends on thefile-loader
, so both need to be installed (only one is introduced) options
In thelimit
: Comments in the following code
const {resolve} = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports={
entry:'./src/index.js'.output: {filename:"build.js".path:resolve(__dirname,"build")},module: {rules:[
{
test:/\.less$/,
use:[
"style-loader"."css-loader"."less-loader",]}, {test:/\.(jpg|png|gif|jpeg)$/.// Use the single loader writing format
// Download two packages, url-loader and file-loader, because url-loader relies on file-loader to work, so you need to download two packages
loader:"url-loader".options: {// Effect: Images smaller than 8KB are base64 processed
// Advantages: Reduce the number of requests and reduce server stress
// Disadvantages: Larger image size (slower file request)
limit:8 * 1024}}},plugins: [new HtmlWebpackPlugin({
template:"./src/index.html"})].mode:"development"
}
Copy the code
New problems:
Url-loader can process CSS images, but for HTML images, the packed build/index.html file is opened by the browser and the image cannot be displayed.
- This is the time
html-loader
url-loader
andhtml-loader
In theoptions
theesModule
All set tofalse
- Reason: Shutdown
url-loader
thees6module
Modular, usingcommonjs
The modular
- Reason: Shutdown
name:"[hash:10].[ext]"
:[hash:10]
:hash
The value of the former10
position[ext]
: takes the original file name extension
const {resolve} = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports={
entry:'./src/index.js'.output: {filename:"build.js".path:resolve(__dirname,"build")},module: {rules:[
{
test:/\.less$/,
use:[
"style-loader"."css-loader"."less-loader",]}, {test:/\.(jpg|png|gif|jpeg)$/.// Use the single loader writing format
// Download two packages, url-loader and file-loader, because url-loader relies on file-loader to work, so you need to download two packages
loader:"url-loader".options: {// Effect: Images smaller than 8KB are base64 processed
// Advantages: Reduce the number of requests and reduce server stress
// Disadvantages: Larger image size (slower file request)
limit:8 * 1024.esModule:false.// Rename the image
name:"[hash:10].[ext]"}, {},test:/\.html$/.// html-loader is responsible for importing images from HTML that can be processed by urL-loader
loader: "html-loader".options: {
esModule: false}}},plugins: [new HtmlWebpackPlugin({
template:"./src/index.html"})].mode:"development"
}
Copy the code
4. Packaging of other resources:
Directory structure:
SRC ├─ └ iconfont.css ├─ └ Iconfont.eot ├─ └ Iconfont.svg ├─ └ Iconfont.ttF ├─ └ Iconfont.woff ├─index.html ├.jsCopy the code
The iconfont resource is used here for testing purposes
webpack.config.js
- through
rules
Objects in theexclude:/\.(css|js|html)$/
Excluding those suffixes leaves other files (font files, etc.) - through
file-loader
To handle the loading of other files
const {resolve} = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry:"./src/index.js".output: {filename:"build.js".path:resolve(__dirname,"build")},module: {rules:[
{
test:/\.css$/,
use:[
"style-loader"."css-loader",]}, {// Use exclude to exclude these suffixes and all other resources are left
exclude:/\.(css|js|html)$/,
loader:"file-loader"}},plugins: [new HtmlWebpackPlugin({
template:"./src/index.html"})].mode:"development"
}
Copy the code
4.webpack-dev-server
Modifying files in SRC requires manual compilation, and webpack-dev-server makes it possible to automate this
Go directly to webpack.config.js:
contentBase
: Path after the project is builtcompress
: Enable or notgzip
The compressionport
: the port numberopen
: Automatically opens after compiling
const {resolve} = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry:"./src/index.js".output: {filename:"build.js".path:resolve(__dirname,"build")},module: {rules:[
{
test:/\.css$/,
use:[
"style-loader"."css-loader",]}, {// Use exclude to exclude these suffixes and all other resources are left
exclude:/\.(css|js|html)$/,
loader:"file-loader"}},plugins: [new HtmlWebpackPlugin({
template:"./src/index.html"})].mode:"development".devServer: {// The path after the project is built
contentBase:resolve(__dirname,"build"),
// Start gzip compression
compress:true./ / the port number
port:3000.// Automatically open the browser after compiling
open:true}}Copy the code