前端工程化之 css sprites 精灵图运用

作者: tww844475003 分类: 前端开发 发布时间: 2021-10-19 20:44

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);
  });
前端开发那点事
微信公众号搜索“前端开发那点事”

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注