Skip to content

Instantly share code, notes, and snippets.

@leovoel
Created January 21, 2017 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leovoel/5d5fc6ae6e2c713a639a0da012efbb3c to your computer and use it in GitHub Desktop.
Save leovoel/5d5fc6ae6e2c713a639a0da012efbb3c to your computer and use it in GitHub Desktop.
const fs = require('fs');
const postcss = require('postcss');
const selectorParser = require('postcss-selector-parser');
const combineDuplicates = require('postcss-combine-duplicated-selectors');
const discardDuplicates = require('postcss-discard-duplicates');
const perfectionist = require('perfectionist');
const search = postcss.plugin('postcss-css-search', (options) => {
if (!options.what) {
throw new Error("Please set options.what to the class you're looking for");
}
let check;
if (options.mode === 'contains') {
if (options.what instanceof Array) {
check = (classes) => {
return !!classes.filter(c => options.what.indexOf(c.value) !== -1).length;
};
} else {
check = (classes) => {
return !!classes.filter(c => c.value === options.what).length;
};
}
} else if (options.mode === 'isLast') {
if (options.what instanceof Array) {
check = (classes) => {
return options.what.indexOf(classes[classes.length - 1].value) !== -1;
};
} else {
check = (classes) => {
return classes[classes.length - 1].value === options.what;
};
}
} else {
throw new Error(`Unrecognized mode ${options.mode}`);
}
return root => {
root.walkRules(rule => {
const rawSelectors = rule.selector;
let shouldDeleteRule = true;
selectorParser((selectors) => {
selectors.each((selector) => {
const classes = selector.filter(n => n.type === 'class');
if (classes.length) {
shouldDeleteRule = !check(classes);
if (shouldDeleteRule) {
return false;
}
}
});
}).process(rawSelectors);
if (shouldDeleteRule) {
rule.remove();
}
});
root.walkAtRules(atRule => {
if (!atRule.nodes.length || atRule.name === 'font-face') {
atRule.remove();
}
});
};
});
const inputFilename = 'test.css';
const outputFilename = 'test-output.css';
fs.readFile(inputFilename, (error, css) => {
if (error) {
throw error;
}
postcss([
search({ mode: 'contains', what: 'embed' }),
combineDuplicates,
discardDuplicates,
perfectionist({ format: 'expanded', cascade: false, indentSize: 2 })
]).process(css, { from: inputFilename, to: outputFilename })
.then(result => {
fs.writeFile(outputFilename, result.css, (error) => {
if (error) {
throw error;
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment