-
这次来处理对图片的打包
-
首先需要下载以下loader
npm install file-loader -D
{
test:/\.(png|jpg|gif)$/,
use:['file-loader']
},
-
在module的rules新加入规则
-
引入图片的方式为 import img from '路径' 此时是在JS文件中引入图片
-
在css中引入图片直接用url('路径') 的方式就会打包
-
在html中引入img图片需要安装另一个loader
npm install html-withimg-loader -D
-
需要在module的rules加入新的规则
{
test:/\.html$/,
use:'html-withimg-loader'
},
-
此时在html中引入的img图片就可以被一起打包了
-
到这里可以进行一些优化,比如小一点的图片,转换成base64编码的方式来减少http请求
npm install url-loader -D
-
module里的rules规则变成
{
test:/\.(png|jpg|gif)$/,
use:{
loader:'url-loader',
options:{
limit:100*1024
}
}
},
-
options里的limit代表如果大于这个值就不用base64的方式进行打包
-
可以进行打包分类
{
test:/\.(png|jpg|gif)$/,
use:{
loader:'url-loader',
options:{
limit:10*1024,
outputPath:'/img/' // 打包后的路径
}
}
},
-
同样css也可以打包分类
new MiniCssExtractPlugin({
filename:'main.css'
}),
//改为
new MiniCssExtractPlugin({
filename:'css/main.css'
}),
-
可以给每一个资源加上CDN地址,在webpack配置文件中output属性中加入publicPath
output:{
filename:'bundle.[hash:8].js',
path:path.resolve(__dirname,'./dist'),
publicPath:'https://www.test.com'
},
-
上面这种情况是给所有资源都加CDN地址
-
如果只需要给某一个资源加上CDN地址,在他对一个loader的options中配置publicPath就可以了,这里用图片loader举例
{
test:/\.(png|jpg|gif)$/,
use:{
loader:'url-loader',
options:{
limit:10*1024,
outputPath:'/img/',
publicPath: 'https://www.test.com'
}
}
},