Kal*_*nin 5 javascript css optimization abstract-syntax-tree
我有风格
.a{width: 10px;}
...
.a{width: 20px;}
Run Code Online (Sandbox Code Playgroud)
很明显,第一个选择器未使用。我正在寻找一个工具,可以为我提供有关 css 中此类位置的信息。例如getUnusedRule(styles)-> style.css、规则、选择器等处的行号。别的。
第二种情况是通知过于嵌套的选择器
.a .b .c .d{...}
Run Code Online (Sandbox Code Playgroud)
getTooLongSelectors(styles, maxNestingNum)-> 在源代码中查找位置的信息
我不想缩小输出CSS,但需要在代码中找到这些地方并手动修复它。重点不是缩小代码,而是使源代码更准确,以便更好地维护并防止堆积不必要的东西。
我认为它可能是 css AST 分析器,它输出用于手动源代码改进的信息。
我更喜欢基于javascript的工具,我们团队中有一些 js 程序。
有任何想法吗?不仅欢迎现成的工具,而且欢迎思维方式。
您想要的基本上是一个 linter,也许您不需要构建自己的。您可能对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]);
});
Run Code Online (Sandbox Code Playgroud)