腾讯DeepOcean原创文章:dopro.io/webpack-spr…css
一、须要合成的雪碧图icon统一放在src / assets / sprite文件夹下html
二、在src / img 会生成一份以上级目录名称命名的雪碧图,如icon文件夹中用到的图标拼合成icon.png前端
三、雪碧图从上到下的方式排列,而且每一个图标间隔20px,如图所示webpack
四、在sass中编写,按需合并。git
五、编译后获得的样式以下,包括width、height也一同输出github
一种是以webpack-spritesmith、postcss-sprites为表明的插件,webpack-spritesmith主要的运行方式是会预先把sprite目录中的图标拼合好,页面主要依赖生成后的雪碧图。而postcss-sprites则是经过对已经生成的 CSS 文件进行分析,将其中的 background 或 background-image 做为依赖收集,合并成雪碧图后再将相关参数替换。web
第二种是loader处理方式,不过网上基本上没有很好的方案,好比说这种前端工程化
这种经过注释的方式来识别并非很好。sass
目前市面上的方案都不能知足咱们的个性化要求,相对于插件针对某一文件夹/文件处理方式,咱们更但愿采用loader链式处理的方式来实现。微信
这里主要利用spritesmith开源项目来进行开发,spritesmith很强大,它能够比较灵活的合成雪碧图,经过相应的API能够得到图标的相关信息。
其中sprites是须要被合成的图片路径,里面包含了图标的绝对路径
Spritesmith.run({src: sprites,algorithm:'top-down',padding: 20}, function handleResult (err, result) {
if(err) {
throw err;
}
});
Spritesmith.run({src: sprites,algorithm:'top-down',padding: 20}, function handleResult (err, result) {
if(err) {
throw err;
}
});
利用这些信息咱们能够对返回的样式进行从新处理,知足前面第5点的样式要求
let imageW = image.width;
let imageH = image.height;
if(mobile){
imageW = imageW/2;
imageH = imageH/2;
}
let imgWidth = 'width:' + imageW + 'px;';
let imgHeight = 'height:' + imageH + 'px;';
if(i < afterContent.length) {
if(afterContent[i] == ';') {
end = i + 1;
afterContent = afterContent.substring(0, end) + backgroundSize+ imgWidth+ '\n' + imgHeight + afterContent.substring(end);
} else {
end = i;
afterContent = afterContent.substring(0, end) + ';\n' + backgroundSize +imgWidth+ '\n' + imgHeight+ afterContent.substring(end);
}
}
let imagePosX = image.x;
let imagePosY = image.y;
if(mobile){
imagePosX = imagePosX/2;
imagePosY = imagePosY/2;
}
let imageX = image.x == 0 ? ' 0' : ' -' + imagePosX + 'px';
let imageY = image.y == 0 ? ' 0' : ' -' + imagePosY + 'px';
let imagePosition = '';
if(image.x || image.y){
imagePosition = imageX + imageY;
}
let cssVal = 'url("' + spriteRelativePath + '")' + imagePosition;
module:{
rules:[
{
test:/\.(scss|css)$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
publicPath: '../../',
use: [{
loader:'css-loader'
},{
loader:'isprite-loader',
options:{
outputPath:'./src/assets/img/',
mobile:true
}
},{
loader:'sass-loader'
}],
})
},
]
}
每个业务都有不一样的需求场景,这种方式可能不必定适用于其余项目,但愿对你们有所帮助。
附上demo