2016-07-22 119 views
2

我的風格CSS AST分析

.a{width: 10px;} 
... 
.a{width: 20px;} 

是顯而易見的是第一選擇使用。 我搜索一個工具,給我關於這些地方在CSS的信息。 eg getUnusedRule(styles) - > style.css,rule,selector,smth的行號。其他。

第二種情況是通知有關太嵌套選擇

.a .b .c .d{...} 

getTooLongSelectors(styles, maxNestingNum) - >信息找到源代碼的地方

我不想來縮小輸出的CSS,但需要找到這樣的地方代碼並手動修復它。 關鍵是不要簡化代碼,而是爲了使源代碼更加準確,以便更好地維護並防止堆不必要的事情。

我認爲它可能是css AST分析器,它輸出手動源代碼改進的信息。

我好javascript基於工具,我們在團隊中有一些js程序。

任何想法?不只是現成的工具,還有歡迎的思維方式。

+0

我更新了我的答案,共享可用腳本的NodeJS,可以處理多個掉毛,而且目前驗證每一個選擇在小於等於20個字符 – tzi

回答

1

你想要的基本上是棉絨,也許你不需要自己建立。您可能對CSSLint感興趣。它由nodeJS製作並提出了許多預編碼規則。

否則,您可以使用reworkCSS訪問簡單的AST。

'use strict'; 

var fs = require('fs'); 
var path = require('path'); 
var rework = require('css'); 

// Usage control 
if (process.argv.length != 3) { 
    console.log('Usage: node index.js ./path/to/my/stylesheet.css'); 
    process.exit(); 
} 

// Read a file (relative path) with node 
function readFile(fileName, cb) { 
    var filePath = path.join(__dirname, fileName); 
    fs.readFile(filePath, {encoding: 'utf-8'}, function (error, data) { 
     if (error) { 
      console.log(error); 
      process.exit(); 
     } 

     cb(data); 
    }); 
} 

// A nice way to walk through every rule 
function walkRules(rules, linters) { 
    rules.forEach(function(rule) { 
     if (rule.rules) { 
      walkRules(rule.rules); 
     } 
     linters.forEach(function(linter){ 
      linter(rule); 
     }); 
    }); 
} 

// A custom linter 
function checkRule(rule) { 
    if (rule.selectors) { 
     rule.selectors.forEach(function(selector) { 
      if (selector.length > 20) { 
       console.log('Line ' + rule.position.start.line + ': too long selector "' + selector + '"'); 
      } 
     }); 
    } 
} 

// Main part 
var fileName = process.argv[2]; 
readFile(fileName, function(css) { 
    var ast = rework.parse(css); 
    walkRules(ast.stylesheet.rules, [checkRule]); 
});