Introduction to WebPack
I studied several times, but I still forgot every time. I made notes while studying to deepen my impression.
1. Webpack profile
Description: Webpack is a static module packaging tool for modern JavaScript applications. 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.
2. Five core concepts of Webpack
2.1 Entry
The Entry indicates which file webPack starts packing as the Entry point, analyzing and building the internal dependency diagram
2.2 the Output
Output indicates where the Output of the resource bundles packaged by Webapck goes and how to name them.
2.3 Loader
Loader enables Webpack to handle non-javascript files (Webpack itself only understands Javascript)
3.3 the Plugins
Plugins can be used to perform a wider range of tasks, from packaging optimization and compression to redefining variables in a new environment.
3.4 Mode
Mode instructs Webpack to use the configuration of the corresponding Mode. By selecting one of development, Production, or None to set the mode parameter, you can enable the optimizations built into WebPack for that environment. The default value is production.
3. Webpack early experience
3.1 Initializing the Project
Enter in the command window
npm init
Copy the code
Initialize the project and fill in the relevant information as required. I didn’t fill in any information here
3.2 Installation Dependencies
- Run the command to install dependencies globally
npm i webpack webpack-cli -g
Copy the code
- Run the command to install it locally
npm i webpack webpack-cli -D
Copy the code
Create a directory structure as shown in the following figure
SRC stores resource files. Index.js webpack entry starting point file; Build as the output directory of the packaged files;
Enter it in the index.js file
function add(x, y) {
return x + y;
}
console.log(add(1.2));
Copy the code
Execute the following commands on the command line, respectively, to see the differences in the packaged build output file
Webpack. / SRC/index.js-o./build --mode=productionCopy the code
conclusion
- Webpack can handle JS/JSON resources, not CSS/IMG resources
- Production and development environments compile ES6 modules into modularity that browsers recognize
- The production environment has one more compressed JS code than the development environment
Configure CSS styles and static resources
4. Package style resources
- Create demo. The file structure is as follows
- Package style resources required
CSS - loader, the style - loader
Two dependencies. Download the dependencies and execute the following command
npm i css-loader style-loader -D
Copy the code
- Configure the webpack.config.js configuration file
// It is mainly used to write the configuration automatic prompt, but it needs to be annotated when repackaging, otherwise an error will be reported
// import { Configuration } from "webpack";
const { resolve } = require("path");
/ * * *@type {Configuration}* /
const config = {
entry: "./src/index.js".output: {
filename: "build.js".path: resolve(__dirname, "build"),},module: {
rules: [{test: /\.css$/,
use: [
// Use Loaders in data are executed in sequence
"style-loader"."css-loader",],},],},plugins: [].mode: "development"};module.exports = config;
Copy the code
- In the index.css file, the HTML, body tag provides a style, and the index.js file is introduced
index.css
html.body{
background-color: pink;
}
Copy the code
index.js
import "./index.css";
Copy the code
After the configuration is complete, run the webpack command.
webpack
Copy the code
- After the package is completed, we need to test whether the style file is successfully packaged. In the build folder, create an index. HTML file and import the packed build.js file. When you open the page in your browser, the style file has taken effect.
But in our development process, instead of using CSS style files, we might use less sass style files, so what should we do?
We just need to add the rules for less and sass to the rules in the module in webpack.config.js. Here, take less as an example.
- The installation
Less - loader, less
Rely on - Add rules rules
{
test: /\.less$/,
use: ["style-loader"."css-loader"."less-loader"],}Copy the code
- Index. less imports into the index.js file
- perform
webpack
The command
- Has to take effect
5. Package HTML resources
- Create demo. The structure is as follows
- The installation
html-webpack-plugin
Plugin.
npm i html-webpack-plugin -D
Copy the code
- Configure webpack.config.js as follows
Add the following
const HtmlWepackPlugin = require("html-webpack-plugin");
plugins: [
new HtmlWepackPlugin({
// copy the "./ SRC /index.html" file
template: "./src/index.html",})],Copy the code
- Complete configuration
// import { Configuration } from "webpack";
const { resolve } = require("path");
const HtmlWepackPlugin = require("html-webpack-plugin");
/ * * *@type {Configuration}* /
const config = {
entry: "./src/index.js".output: {
filename: "build.js".path: resolve(__dirname, "build"),},module: {
rules: []},plugins: [
new HtmlWepackPlugin({
// copy the "./ SRC /index.html" file
template: "./src/index.html",})],mode: "development"};module.exports = config;
Copy the code
- Execute pack command
webpack
6. Pack your photo resources
- The demo file structure is as follows:
- Packaging image resources requires installation
Url - loader, file - loader
Install the url – loader
npm i url-loader file-loader -D
Copy the code
- Configure the webpack.config.js file and add the following rules to rules
{
test: /\.(jpg|png|gif)$/,
loader: "url-loader".options: {
// Images smaller than 8KB are base64 processed
limit: 8 * 1024.// Rename the image
// image Prints images to the images folder
// [name] the original name of the image
// [hash:10] Takes the first 10 digits of the image hash
// [ext] takes the original extension of the image
name: "images/[name].[hash:10].[ext]",}},Copy the code
-
Add styles to the index.less file and import images. Import the index.js file
-
Run the webpack command, and the result is as follows: The packed image resources have taken effect
- The packing results are also executed as we set them up
If we write an IMG tag to an HTML page, we will not be able to package it as described above, so we need to configure webpack.config.js
- The installation
html-loader
npm i html-loader -D
Copy the code
- Configuration rules
{
test: /\.html$/.// Process the IMG image in HTML (import img to urL-loader for processing)
loader: "html-loader".options: {
// Because url-loader uses ES6 modularized parsing by default, htMl-loader uses commonJS to parse images
// Disable THE ES6 modularization of url-loader and use commonJS parsing
esModule: false,}},Copy the code
- Re-execute the package command, and the IMG tag written in the HTML page is displayed
Note that we need to turn off the esModule, because because url-loader uses ES6 modular parsing by default and htMl-loader introduces images, there will be problems with commonJS parsing and images will not be displayed
7. Configuration devserver
When writing or modifying the code in the environment we configured before, we need to re-pack the webpack after each modification, and then open the packed HTNL file in the browser, which is very inconvenient, so we need to configure DevServer here
- To install devServer, run the following command
npm i webpack-dev-server -D
Copy the code
- Add the following code to webpack.config.js
devServer: {
// Project build path
contentBase: resolve(__dirname, "build"),
// Start gzip compression
compress: true./ / the port number
port: 3000.// Automatically open the browser
open: true,},Copy the code
- Execute the command
npx webpack server
On startup, we can see that the page opens in the default browser, and a port 3000 is launched,http://localhost:3000You can see our results.
We modify the code after saving the code will be automatically edited, and automatically refresh the page, so that more efficient coding
8. Extract CSS styles into separate style files
The previous configuration, the packaged CSS style code is all in the JS file, now we need to separate the CSS into a CSS file
- Create new A.css and b.css files, write styles respectively, and introduce style files in index.js. Structure is as follows
- The installation
mini-css-extract-plugin
The plug-in
npm i mini-css-extract-plugin -D
Copy the code
- Configuration webpack. Config. Js
- To obtain
MiniCssExtractPlugin
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
Copy the code
- You need to
style-loader
replaceMiniCssExtractPlugin.loader
use: [
// "style-loader",
// Replace style-loader to extract CSS files as separate files
MiniCssExtractPlugin.loader,
"css-loader",].Copy the code
- Add the plug-in
MiniCssExtractPlugin
plugins: [
new HtmlWebpackPlugin({
template: "./index.html",}).new MiniCssExtractPlugin({
filename: "css/build.css",})],Copy the code
- Execute the package command, the package result is as follows, the CSS style file is extracted to build.css
9. CSS compatibility
In front-end development, we may encounter a variety of browsers and different browser versions, so we need to adapt our CSS to all browser versions.
- Installing a plug-in
npm i postcss-loader postcss-preset-env -D
Copy the code
- Configuration webpack. Config. Js
- add
postcss-loader
/** * CSS compatibility handling: Postcss -->postcss-loader postCSs-preset -env * Help PostCSS find the configuration in package.json browserList and load the specified CSS compatibility */
// Use the default loader location
// 'postcss-loader,
// Change the loader location
{
loader: "postcss-loader".options: {
postcssOptions: {
ident: "postcss"./ / postcss plug-in
plugins: [require("postcss-preset-env")],}}},Copy the code
- Add it in package.json
browserslist
"browserslist": {
"development": [
"last 1 chrome version"."last 1 firefox version"."last 1 safari version"]."production": [
"0.2%" >."not dead"."not op_mini all"]}Copy the code
- Add cSS3 properties to the CSS to test whether the PostCSS compatibility takes effect
- Check whether compatibility properties are added to the CSS3 properties in the build. CSS package
10. CSS compression
- The installation
optimize-css-assets-webpack-plugin
npm i optimize-css-assets-webpack-plugin -D
Copy the code
- Configuration webpack. Config. Js
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");
plugins: [
new OptimizeCssAssetsWebpackPlugin(),
],
Copy the code
- Complete webpack.config.js configuration
//import { Configuration } from "webpack";
const { resolve } = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");
// process.env.NODE_ENV = "development";
//optimize-css-assets-webpack-plugin
/ * * *@type {Configuration}* /
const config = {
entry: "./src/js/index.js".output: {
filename: "js/build.js".path: resolve(__dirname, "build"),},module: {
rules: [{test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
{
loader: "postcss-loader".options: {
postcssOptions: {
ident: "postcss"./ / postcss plug-in
plugins: [require("postcss-preset-env"],},},},],},plugins: [
new HtmlWebpackPlugin({
template: "./index.html",}).new MiniCssExtractPlugin({
filename: "css/build.css",}).new OptimizeCssAssetsWebpackPlugin(),
],
mode: "development"};module.exports = config;
Copy the code
Compress JS and HTML
-
To compress the JS code, just change the development mode to production environment.
-
HTML compression
plugins: [
new HtmlWebpackPlugin({
template: "./index.html"./ / HTML compression
minify: {
// Remove whitespace
collapseWhitespace: true.// Remove comments
removeComments: true,}})],Copy the code