"devDependencies": {
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
"file-loader": "^3.0.1",
"url-loader": "^1.1.2"
},
main.css
body {
/* background: yellow; */
/* 29kb 效果 background: url(images/dog1-afa6a.min.webp); */
/* background: url("../img/dog1.webp"); */
/* 4.4kb 效果 background: url(data:image/webp;base64,UklGRpYRA。。。。 */
background: url("../img/hlw.webp")
/* 注意点:配置了图片的大小压缩 小于20kb 转化为base64 */
}
main.js
import "./css/main.css"
publicPath: './', // 配置项目的 公告路径module.exports = {
// webpack执行打包的唯一入口
entry: {
main: [path.resolve(__dirname, './src/main.js')],
},
// 打包的输入
output: {
publicPath: './', // 配置项目的 公告路径
// 将所有依赖的模块合并输出到main_xxxxxx.js,xxxxxx为随机生成的6位hash码
//当内容有改变时,hash会变化,防止缓存原因导致修改不更新
filename: 'js/[name]_[contenthash:6].js',
// 输出文件的存放路径, 必须是绝对路径
path: path.resolve(__dirname, "./dist")
},
// loader相关配置
module: {
rules: [
{
test: /\.(png|jpg|jpeg|gif|webp)$/,
use: [{
loader: 'url-loader',
options: {
name: '[name]-[hash:5].min.[ext]',
outputPath: 'images/', //输出到 images 文件夹
limit: 20000 //把小于 20kb 的文件转成 Base64 的格式
}
}]
}
]
},
plugins: [
]
}
大于20kb正常加载url,小于20kb转化为 base64
大于20kb正常加载url 还有再dist之中生成图片


小于20kb转化为base64展示,不再dist之中生成图片

"devDependencies": {
"image-webpack-loader": "^4.6.0"
},
module.exports = {
// loader相关配置
module: {
rules: [
{
test: /\.(png|jpg|jpeg|gif|webp)$/,
use: [{
loader: 'url-loader',
options: {
name: '[name]-[hash:5].min.[ext]',
outputPath: 'images/', //输出到 images 文件夹
limit: 20000 //把小于 20kb 的文件转成 Base64 的格式
}
},
// 使用 image-webpack-loader 对图片进行压缩
{
loader: "image-webpack-loader",
options: {
mozjpeg: { progressive: true, quality: 65 },
optipng: { enabled: false },
pngquant: { quality: '65-90', speed: 4 },
gifsicle: { interlaced: false },
webp: { quality: 75 }
}
},
]
}
]
},
}

