前端工程化之 css sprites 精灵图运用
postcss-sprites
一款图片精灵生成工具。
- node 场景运用
// 安装
npm i -D postcss-sprites
// css
// input
.all {
background: url('../images/all.png') no-repeat;
}
.back {
background: url('../images/back.png') no-repeat;
}
.cart {
background: url('../images/cart.png') no-repeat;
}
.category {
background: url('../images/category.png') no-repeat;
}
.close {
background: url('../images/close.png') no-repeat;
}
.comments {
background: url('../images/comments.png') no-repeat;
}
.cry {
background: url('../images/cry.png') no-repeat;
}
.delete {
background: url('../images/delete.png') no-repeat;
}
.edit {
background: url('../images/edit.png') no-repeat;
}
// output
.all {
background-image: url(images/sprite.png);
background-position: 0px 0px;
background-size: 96px 96px;
}
.back {
background-image: url(images/sprite.png);
background-position: -32px 0px;
background-size: 96px 96px;
}
.cart {
background-image: url(images/sprite.png);
background-position: 0px -32px;
background-size: 96px 96px;
}
.category {
background-image: url(images/sprite.png);
background-position: -32px -32px;
background-size: 96px 96px;
}
.close {
background-image: url(images/sprite.png);
background-position: -64px 0px;
background-size: 96px 96px;
}
.comments {
background-image: url(images/sprite.png);
background-position: -64px -32px;
background-size: 96px 96px;
}
.cry {
background-image: url(images/sprite.png);
background-position: 0px -64px;
background-size: 96px 96px;
}
.delete {
background-image: url(images/sprite.png);
background-position: -32px -64px;
background-size: 96px 96px;
}
.edit {
background-image: url(images/sprite.png);
background-position: -64px -64px;
background-size: 96px 96px;
}
// index.js
var fs = require('fs');
var postcss = require('postcss');
var sprites = require('postcss-sprites');
var css = fs.readFileSync('./css/style.css', 'utf8');
var opts = {
stylesheetPath: './dist',
spritePath: './dist/images/'
};
postcss([sprites(opts)])
.process(css, {
from: './css/style.css',
to: './dist/style.css'
})
.then(function (result) {
fs.writeFileSync('./dist/style.css', result.css);
});