聊聊CSS postproccessors

 

阿里媽媽 @一絲 準備發佈其CSSGrace,即CSS後處理插件,因而順便聊聊CSS postprocessors。css

從Rework提及

Rework是TJ大神開發的CSS預處理框架。但爲何會出現呢?TJ大神如此回答:html

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預處理框架,經過插件,可自定義擴展功能。android

我用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。讓咱們看看他到底幹了什麼?ios

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.git

因此呢?若是咱們寫了:github

a {
    display: flex;
}

則通過Autoprefixer,會變成:web

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

而且這些hack數據是從caniuse獲取的,因此能根據你的須要設置你須要兼容的瀏覽器。Sounds good!這更像polyfill,咱們只用按照標準寫就行了,polyfill會幫忙處理兼容性,以後若是無需兼容,其會自動去除。chrome

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等如此強大的預處理器未必是必需品。

相關文章
相關標籤/搜索