使用插件webpack-spritesmith生成雪碧图
1、安装webpack-spritesmith;
npm install --save-dev webpack-spritesmith
2.配置webpack.config.js
new SpritesmithPlugin({ //生成的雪碧图本身就压缩了图片大小
src: {
cwd: path.resolve(__dirname, 'src/image/icon'), //准备合并成sprit的图片存放文件夹
glob: '*.png' //哪类图片
},
target: {
image: path.resolve(__dirname, 'dist/sprites/sprites.png'), // sprite图片保存路径
css: path.resolve(__dirname, 'dist/sprites/_sprites.css') // 生成的css保存在哪里
},
apiOptions: {
cssImageRef: "../sprites/sprites.png" //css根据该指引找到sprite图
}
}),
贴一张目录
3、执行webpack打包指令,执行后打包生成dist/sprites/文件
4、index.html文件中引入sprite.css,如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webpack</title>
<link href="bundle.3a78e3af7afe10200470.css" rel="stylesheet"></head>
<link href="sprites/_sprites.css" rel="stylesheet"> //引用就可以了
</head>
<body>
<!--测试webpack-->
<div class="test">测试webpack</div>
<div class="test1">测试webpack1</div>
<div class="icon-a">a</div> //需要的地方来用就可以了
<div class="icon-b">b</div>
<script type="text/javascript" src="bundle-3a78e3af7afe10200470.js"></script>
</body>
</html>
合成后的sprites.png
合成后的sprites.css
.icon-a { //名称为icon+图片名
background-image: url(../sprites/sprites.png);
background-position: 0px 0px;
width: 50px;
height: 50px;
}
.icon-b {
background-image: url(../sprites/sprites.png);
background-position: -50px 0px;
width: 50px;
height: 50px;
}
.icon-c {
background-image: url(../sprites/sprites.png);
background-position: 0px -50px;
width: 50px;
height: 50px;
}
5.适用的场景