核心概念
- Webpack:模块打包工具,适合中大型项目
- Vite:新一代前端构建工具,开发启动快
- Rollup:专注于打包库的工具
一、Webpack 核心概念
1.1 五大核心模块
| 模块 | 说明 | 配置示例 |
|---|---|---|
| entry | 入口,打包起点 | entry: './src/index.js' |
| output | 出口,打包结果 | output: { dir: 'dist' } |
| loader | 转换器,处理非 JS 文件 | loader: 'babel-loader' |
| plugins | 插件,扩展功能 | plugins: [new HtmlWebpackPlugin()] |
| mode | 模式 | development / production |
1.2 核心功能
- 模块转换:将 ES6+、TypeScript、Vue 等转换为浏览器可识别的代码
- 资源处理:文件合并拆分、图片压缩、代码压缩
- 开发支持:热模块替换 (HMR)、Source Map、开发服务器
二、Webpack Loader
2.1 常用 Loader 大全
| Loader | 作用 | 安装命令 |
|---|---|---|
babel-loader | ES6+ 转 ES5 | npm i -D babel-loader @babel/core |
css-loader | 解析 CSS 的 import 和 url | npm i -D css-loader |
style-loader | 将 CSS 插入 style 标签 | npm i -D style-loader |
sass-loader | 编译 Sass/SCSS | npm i -D sass-loader sass |
less-loader | 编译 Less | npm i -D less-loader less |
postcss-loader | 处理 CSS 兼容性 | npm i -D postcss-loader postcss |
url-loader | 转文件为 base64 | npm i -D url-loader |
file-loader | 处理文件引用 | npm i -D file-loader |
image-webpack-loader | 图片压缩 | npm i -D image-webpack-loader |
ts-loader | TypeScript 编译 | npm i -D ts-loader typescript |
vue-loader | 处理 Vue 单文件组件 | npm i -D vue-loader |
html-loader | 处理 HTML 中的图片引用 | npm i -D html-loader |
Loader 执行顺序
- 从右向左 / 从下到上 执行
- 例如:
use: ['style-loader', 'css-loader', 'sass-loader']- 先执行
sass-loader,再执行css-loader,最后执行style-loader
2.2 Loader 配置示例
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.(png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 8192, // 小于 8kb 转 base64
name: 'img/[name].[hash:8].[ext]',
},
},
},
],
},
};三、Webpack Plugins
3.1 常用插件大全
| Plugin | 作用 | 安装命令 |
|---|---|---|
html-webpack-plugin | 生成 HTML 文件 | npm i -D html-webpack-plugin |
clean-webpack-plugin | 清理构建目录 | npm i -D clean-webpack-plugin |
mini-css-extract-plugin | 提取 CSS 为独立文件 | npm i -D mini-css-extract-plugin |
css-minimizer-webpack-plugin | 压缩 CSS | npm i -D css-minimizer-webpack-plugin |
terser-webpack-plugin | 压缩 JS | 内置,Webpack5 自带 |
eslint-webpack-plugin | ESLint 检查 | npm i -D eslint-webpack-plugin |
copy-webpack-plugin | 复制文件到构建目录 | npm i -D copy-webpack-plugin |
webpack-bundle-analyzer | 打包体积分析 | npm i -D webpack-bundle-analyzer |
compression-webpack-plugin | 压缩资源 (Gzip) | npm i -D compression-webpack-plugin |
3.2 Plugin 配置示例
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
plugins: [
// 清理构建目录
new CleanWebpackPlugin(),
// 生成 HTML
new HtmlWebpackPlugin({
title: '我的应用',
template: './src/index.html',
minify: {
collapseWhitespace: true, // 折叠空白
removeComments: true, // 移除注释
},
}),
// 提取 CSS
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
}),
],
};四、核心概念详解
4.1 Tree Shaking
定义
删除未使用的代码,减小打包体积
前提条件:
- 使用 ES6 Module 语法(
import/export) - 在
production模式下 package.json中设置"sideEffects": false
// ✅ 支持 Tree Shaking
import { debounce } from 'lodash-es';
export const fn = () => {};
// ❌ 不支持 Tree Shaking
const lodash = require('lodash'); // CommonJS4.2 Code Splitting(代码分割)
定义
将代码分割成多个 chunk,按需加载
分割方式:
- 多入口:配置多个 entry
- 动态导入:使用
import()语法 - 提取第三方库:splitChunks 配置
// 动态导入
const Home = () => import('./Home.vue');
// splitChunks 配置
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
priority: 10,
},
},
},
}4.3 Bundle、Chunk、Module 的区别
| 概念 | 说明 |
|---|---|
| Module | 开发中的单个模块,一个文件一个模块 |
| Chunk | 代码块,由多个 Module 组成,用于代码分割 |
| Bundle | 最终输出的打包文件 |
五、Webpack 配置模板
5.1 基础配置
// webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
module: {
rules: [
{ test: /\.js$/, loader: 'babel-loader' },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
],
},
devServer: {
port: 3000,
hot: true,
open: true,
},
};5.2 生产环境配置
// webpack.prod.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'production',
devtool: 'source-map',
optimization: {
minimize: true,
},
});六、Webpack vs Vite
| 特性 | Webpack | Vite |
|---|---|---|
| 启动速度 | 慢(需打包) | 极快(按需编译) |
| 热更新 | 较快 | 极快 |
| 配置复杂度 | 高 | 低 |
| 生态 | 成熟完善 | 快速发展 |
| 适用场景 | 中大型项目 | 中小型项目/库 |
6.1 Vite 优势
// vite.config.js - 简洁的配置
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
server: {
port: 3000,
},
build: {
rollupOptions: {
output: {
manualChunks: {
'vue-vendor': ['vue', 'vue-router', 'pinia'],
},
},
},
},
});