npm install css-sprite gulp gulp-if
var gulp = require('gulp');
var gulpif = require('gulp-if');
gulp.task('sprites', function() {
gulp.src('img/icon/*.png')
.pipe(sprite({
name: 'icon',
style: '_icon.scss',
format: 'png',
orientation: 'left-right', // 或 vertical
cssPath: '#{$icon-sprite-path}',
template: './sprite-tpl.mustache',
processor: 'scss'
}))
.pipe(gulpif('*.png', gulp.dest('img/'), gulp.dest('css/'));
});
{{#items}}
${{name}}: {{px.offset_x}} {{px.offset_y}} {{px.width}} {{px.height}};
{{/items}}
@mixin sprite-width($sprite) { width: nth($sprite, 3); }
@mixin sprite-height($sprite) { height: nth($sprite, 4); }
@mixin sprite-position($sprite) {
$sprite-offset-x: nth($sprite, 1);
$sprite-offset-y: nth($sprite, 2);
background-position: $sprite-offset-x $sprite-offset-y;
}
@mixin sprite($sprite) {
@include sprite-position($sprite);
@include sprite-width($sprite);
@include sprite-height($sprite);
}
{{#sprite}}
.{{class}} {
background-repeat: no-repeat;
overflow: hidden;
border: none;
background: url('{{{escaped_image}}}?v=#{$version}');
@include inline-block();
vertical-align: middle;
font-style: normal;
color: $icon-font-color;
}
{{/sprite}}
{{#items}}
.{{name}} { @include sprite(${{name}}); }
{{/items}}
img/icon.png:合併後的雪碧圖css/_icon.scss:對應的 SCSS 變數與 mixin,直接 @import 使用後續可加 gulp.watch 監聽資料夾自動重建。