本文共 3686 字,大约阅读时间需要 12 分钟。
官网地址:
源代码地址:
来自官方的文档上写着的是是一个插件转换样式表的工具。这些插件能够检验你的、支持变量和混合,转化的新特性语法、行内图片等。
其中一个比较为人所知的插件AutoPrefixer就是出自这里,目前上面已经超过200多个插件在。
all: initial
support to reset all inherit styles.autoprefixer
).@font-face
rules needed in CSS.calc()
grid system by Jeet author.PostCSS can transform styles in any syntax, not just CSS.原文来自:http://caibaojian.com/postcss.html
to write styles in JS or transform React Inline Styles, Radium or JSS.PostCSS最有名的插件是。如名所示,可以自动为你添加浏览器私有前缀。它的添加值会参考及你设定的浏览器支持范围,因此相当可靠。下面是一个示例(以我设定的浏览器支持范围):
.container{ display: flex;}
编译后:
//code from http://caibaojian.com/postcss.html.container{ display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex;}
在刚开始使用PostCSS时,我就想到要用PostCSS实现我在Sass中最常用的特性。所以,我找到了postcss-nested
和postcss-mixins
。将它们结合起来后,就可以做到这样:
@define-mixin clearfix{ &:after{ display: table; clear: both; content: " "; }}.column-container{ color: #333; @mixin clearfix;}
编译后:
.column-container{ color: #333;}.column-container:after{ display: table; clear: both; content: " ";}
到这里,你是否已经有了“预编译器可以做到的它也可以做到”的感觉呢?
我个人推荐结合使用,本文在此只介绍的用法。
-postcss
及插件都是,首先,使用npm install
将它们分别安装到项目目录中(会位于node_modules
)。然后,编辑glupfile.js
,将PostCSS注册为Gulp的一个任务。以下是一个结合使用了Autoprefixer
、postcss-simple-vars
、postcss-mixins
、postcss-nested
4个插件,且生成source map文件的例子:
var gulp = require("gulp");var postcss = require("gulp-postcss");var autoprefixer = require('autoprefixer-core');var postcssSimpleVars = require("postcss-simple-vars");var postcssMixins = require("postcss-mixins");var postcssNested = require("postcss-nested");var sourcemaps = require("gulp-sourcemaps");// Css process.gulp.task("postcss", function(){ var processors = [ postcssMixins, postcssSimpleVars, postcssNested, autoprefixer({ browsers: ["Android 4.1", "iOS 7.1", "Chrome > 31", "ff > 31", "ie >= 10"] })]; return gulp.src(["./stylesheets/src/*.css"]) .pipe(sourcemaps.init()) .pipe(postcss(processors)) .pipe(sourcemaps.write(".")) .pipe(gulp.dest("./stylesheets/dest"));});
在上面这段中,processors
是一个数组,定义了用到的PostCSS插件。PostCSS会按照定义顺序依次执行插件,因此,在结合多个插件使用时,请注意它们的位置。
此外,你可以很容易地创建你自己的转换(还记得前面说过PostCSS的插件都是函数吧?)。例如,下面是一个自定义的转换方法,它将css代码中的带有单位的值,更改为
px
的值。
var custom = function(css, opts){ css.eachDecl(function(decl){ decl.value = decl.value.replace(/\d+rem/, function(str){ return 16 * parseFloat(str) + "px"; }); });};
然后,你将这个方法直接添加到processors
中(就像postcssMixins
那些那样)就可以使用。如果原来有值是3rem
,将变成48px
。
更多:
转载地址:http://unogi.baihongyu.com/