Reputation: 2519
I have styles
.a{width: 10px;}
...
.a{width: 20px;}
Is is obvious that first selector unused.
I search for a tool that give me information about such places in css.
eg getUnusedRule(styles)
-> line number at style.css, rule, selector, smth. else.
The second case is to notify about too nested selectors
.a .b .c .d{...}
getTooLongSelectors(styles, maxNestingNum)
-> info to find place in source code
I dont want to minify output css, but need to find such places in code and fix it manually. The point is not to minify code, but to make source code more accurate for the better maintenance and to prevent pile unnecessary things.
I assume it may be css AST analizer which outputs info for manual source code improvement.
I prefe javascript based tool, we have some js programmes in team.
Any ideas? Not just ready tools but the way of thinking welcome.
Upvotes: 5
Views: 1301
Reputation: 9469
What you want is basically a linter, perhaps you don't need to build your own. You could be interested in CSSLint. It is made with nodeJS and propose a lot of pre-coded rules.
Otherwise, you can use reworkCSS to have access to a simple 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]);
});
Upvotes: 3