index.js 885 B

12345678910111213141516171819202122232425262728293031323334
  1. var postcss = require('postcss');
  2. var assign = require('object-assign');
  3. module.exports = postcss.plugin('postcss-px2units', function (opts) {
  4. opts = opts || {};
  5. opts = assign({
  6. divisor: 1,
  7. multiple: 1,
  8. decimalPlaces: 2,
  9. targetUnits: 'rpx',
  10. comment: 'no'
  11. }, opts);
  12. function repalcePx(str) {
  13. if (!str) {
  14. return '';
  15. }
  16. return str.replace(/\b(\d+(\.\d+)?)px\b/ig, function (match, x) {
  17. var size = x * opts.multiple / opts.divisor;
  18. return size % 1 === 0 ? size + opts.targetUnits : size.toFixed(opts.decimalPlaces) + opts.targetUnits;
  19. });
  20. }
  21. return function (root) {
  22. root.walkDecls(function (decl) {
  23. if (decl && decl.next() && decl.next().type === 'comment' && decl.next().text === opts.comment) {
  24. decl.next().remove();
  25. } else {
  26. decl.value = repalcePx(decl.value);
  27. }
  28. });
  29. };
  30. });