Webpack快速入门
# Webpack快速入门
# Webpack核心概念
- entry:入口模块文件路径
- output: 输出bundle文件路径
- module: 模块,webpack构建对象
- bundle: 输出文件,webpack构建产物
- chunk:中间文件,webpack构建的中间产物
- loader:文件转换器
- plugin:插件,执行特定任务
# 配置的拆分与合并
// 使用 webpack-merge 进行配置合并
const common_config = require('./webpack.base.config')
const {smart: merge} = require('webpack-merge')
const prod_config = {
mode: 'production'
}
module.exports = merge(common_config, prod_config)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 配置开发服务器
devServer:{
port:8080,
contentBase:'./dist',
progress:true,// 打包显示进度条
open:true, // 自动打开浏览器
compress:true, // 启动gzip
proxy:{
'/api':{
target:'http://localhost:8080',
changeOrigin:true,
pathRewrite:{ // 路径替换
'^/api':''
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 处理CSS样式
style-loader 把样式放到style标签里
css-loader 打包css进行合并
scss-loader 处理scss文件打包
postcss-loader 进行兼容性编译,autoprefixer //自动添加浏览器前缀
# 处理图片
file-loader单独打包到img文件夹里,防止首次渲染太慢
url-loader比较小的图片,就转成base64格式,减少http请求
# 多入口
module.exports = {
entry:{
index:'./src/index.js',
other:'./src/other.js'
},
plugins:{
new HtmlWebpackPlugin({ //打包html文件
template:'./src/index.html',
filename:'index.html',
chunks:['index'] // 绑定入口文件
}),
new HtmlWebpackPlugin({
template:'./src/other.html',
filename:'other.html',
chunks:['other']
}),
new CleanWebpackPlugin() // 清理旧的打包文件
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 抽离CSS
MiniCSSExtractPlugin() 把html中的css从style标签中抽离出来成css文件,并用link进行引用
TerserPlugin()压缩js
OptimizeCssAssetsWebpackPlugin()压缩css
使用postcss、postcss-loader、postcss-preset-env及package.json的browserslist做兼容性处理
# 抽离公共代码
公共模块不需要重复打包,可以单独抽离成一个公共模块文件,然后引用即可
第三方模块一般不会改变,不需要业务代码改变之后重新打包,也可以单独抽离成一个公共模块文件,然后引用
import from 同步代码
import() 异步代码
vendor 第三方模块
common 公共模块
splitChunks
1
# 减少代码体积
TreeShaking
babel打包压缩
图片压缩
# 优化代码运行性能
Code Split
将大代码分割成多个,按需加载 import()
统一给chunk命名
preload和prefetch
编辑 (opens new window)