1. Basic overview
The essence of webpack is a third-party module package for analysis and packaging code
- Supports packaging of all types of files
- support less/sass => css
- ES6/7/8 supported => ES5
- Compress code to improve loading speed
2. Installation
- Create a file and run the following commands:
npm init -y
npm i webpack webpack-cli -S
- Run the command npx webpack --mode=development If it is in production mode, you need to change the mode to production. This will automatically generate a dist/main.js file. Introduce this file browser and it will work.
3. Configuration file
- Create a new webpack.config.js file and configure:
const path = require('path');
module.exports = {
mode: 'production',
// 指定入口文件
entry: './src/index.js',
// 输出配置
output: {
// 输出的文件名
filename: 'app.js',
// 输出文件的路径 这个路径要写绝对地址
path: path.resolve(__dirname, 'dist'),
},
};
- Run npx webpack, it will automatically find the configuration in the webpack.config.js file, and generate a packaged file according to the configuration.
- Configuration script: configured in the package.json file
"scripts": {
"serve": "npx webpack"
},
- To run in the future, you only need yarn serve or npm run serve
Four, webpack-dev-server plug-in
1. Function
Start a web server to automatically package code
2. use
- Install npm install webpack-dev-server -S
- Modify the script "serve" in package.json: "npx webpack serve"
- Change the mode to development in webpack.config.js
mode: 'development'
Five, html-webpack-plugin plug-in
1. Function
Let webpack automatically generate html files when packaging
2. use
- Download: npm i --save-dev html-webpack-plugin
- Configuration script: configured in the package.json file
const HtmlWebpackPlugin = require('html-webpack-plugin')
plugins: [
new HtmlWebpackPlugin({
// 指定模版页面
template: 'template.html',
// 根据模版页面生成的页面名字
filename: 'index.html',
})
]
- Then run directly: npm run serve to enter the development stage.
- If the project is going online, configure "build" separately: "npx webpack" Then run npm run build to package index.html and app.js
Official website: webpack https://webpack.js.org/