代码改变世界

聊聊CSS postproccessors

2014-12-05 00:18  Justany_WhiteSnow  阅读(1670)  评论(0编辑  收藏  举报
 

阿里妈妈 @一丝 准备发布其CSSGrace,即CSS后处理插件,于是顺便聊聊CSS postprocessors。

从Rework说起

Rework是TJ大神开发的CSS预处理框架。但为什么会出现呢?TJ大神如此回答:

The simple answer is that Rework caters to a different audience, and provide you the flexibility to craft the preprocessor you want, not the choices the author(s) have force on you.
Our goal with Rework contrasts the others, as it does not provide a higher level language within the CSS documents, Rework’s goal is to make those constructs unnecessary, being the most transparent CSS pre-processor out there.

简单地说,就是从之前的特定CSS预处理器,转而成为通用式CSS预处理框架,通过插件,可自定义扩展功能。

我用compass用得正爽,凭什么用你?

  • 工程师喜欢瞎折腾,满足其DIY乐趣
  • 现代前端,多端多屏、需要不同兼容场景下情况下,CSS预处理器需要深度定制,来看看我们没有深度定制的后果:
    1. 我们经常使用@include border-radius;,可你知道compass这个mixin有啥问题么?
      .btn-default { -webkit-border-radius: 2px } // 仅在 android 2.1, chrome 4, ios_saf 3.2, safari 4 或更早期版本适用
      .btn-default { -moz-border-radius: 2px } // 仅在 firefox 3.6 以前版本适用
      .btn-default { -ms-border-radius: 2px } // 根本不存在 -ms-border-radius
      .btn-default { -o-border-radius: 2px } // 这玩意早就淘汰了
      
    2. 我们也经常用@include transition();,但:
      .course-card .course-agency { -moz-transition: .3s } // 仅在 firefox 15 以前版本适用
      .course-card .course-agency { -o-transition: .3s } // 仅在 opera 12 以前版本适用
      
  • 嵌套很强大,但某些时候也是灾难
    1. 多层嵌套,代码维护的灾难
      多层嵌套地狱
    2. 多层嵌套导致的单页应用代码性能问题,所以Github的CSS规范明确指明Sass嵌套不允许多余三层(之前我们以为仅仅是维护性原因),有兴趣可以围观下 GitHub's CSS Performance

Autoprefixer革命

在我看来真正带来革命的不是postcss,恰恰是他的核心组件Autoprefixer。让我们看看他到底干了什么?

Working with Autoprefixer is simple: just forget about vendor prefixes and write normal CSS according to the latest W3C specs. You don’t need a special language (like Sass) or remember, where you must use mixins.
Just write normal CSS according to the latest W3C specs and Autoprefixer will produce the code for old browsers.

所以呢?如果我们写了:

a {
    display: flex;
}

则经过Autoprefixer,会变成:

a {
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
}

并且这些hack数据是从caniuse获取的,所以能根据你的需要设置你需要兼容的浏览器。Sounds good!这更像polyfill,我们只用按照标准写就好了,polyfill会帮忙处理兼容性,之后如果无需兼容,其会自动去除。

CSSGrace

Make it better!

CSSGrace在我看来主要由于AST的介入,其可能分析出以前preproccessors分析不出来的css错误问题,类似csslint的一些静态分析,以及一丝所说的CSS常见错误,例如:float: left/right 或者 position: absolute 后还写上 display: block,具体参见:http://www.zhihu.com/question/20979831

最后随想

个人感觉未来Web会Web Component化,无论是以W3C标准以HTML为核心的Web Component,还是类似React以Javascript为核心的Web Component,在纵向力度足够细的时候,css样式将趋近与足够简单。

在这种背景下,当处理好作用域的情况下(目前没什么好办法,可能只能将class name写长一点),未来嵌套场景将大大减少,从这一点来看,以前的Sass、LESS等如此强大的预处理器未必是必需品。