|
| 1 | +// |
| 2 | +// Based on https://github.com/dinhani/gulp-css-remove-attributes/blob/master/index.js |
| 3 | +// |
| 4 | +const through = require('through2'); |
| 5 | +const css = require('css'); |
| 6 | + |
| 7 | +const PLUGIN_NAME = 'gulp-css-clean-non-color-attributes'; |
| 8 | +module.exports = function (options) { |
| 9 | + const attributesNotToRemove = [ |
| 10 | + 'color', |
| 11 | + 'background', |
| 12 | + 'background-color', |
| 13 | + 'background-image', |
| 14 | + 'border', |
| 15 | + 'border-color', |
| 16 | + 'border-top', |
| 17 | + 'border-right', |
| 18 | + 'border-bottom', |
| 19 | + 'border-left', |
| 20 | + 'box-shadow', |
| 21 | + 'outline-color', |
| 22 | + 'text-shadow', |
| 23 | + ]; |
| 24 | + |
| 25 | + // INPUT |
| 26 | + function parseInputCss(inputFile, encoding, options) { |
| 27 | + let fileContent = inputFile.contents.toString(encoding); |
| 28 | + let parsedCss = css.parse(fileContent, options); |
| 29 | + return parsedCss; |
| 30 | + } |
| 31 | + |
| 32 | + // PARSING |
| 33 | + function removeCssAttributes(parsedCss) { |
| 34 | + parsedCss.stylesheet.rules = mapRules(parsedCss.stylesheet.rules); |
| 35 | + return parsedCss; |
| 36 | + } |
| 37 | + |
| 38 | + function mapRules(rules) { |
| 39 | + return rules.map((rule) => { |
| 40 | + // only filter rules, the other types are just kept |
| 41 | + if (rule.type === 'rule') { |
| 42 | + rule.declarations = rule.declarations.filter((declaration) => attributesNotToRemove.includes(declaration.property)); |
| 43 | + } |
| 44 | + if (rule.type === 'media') { |
| 45 | + rule.rules = mapRules(rule.rules); |
| 46 | + } |
| 47 | + return rule; |
| 48 | + }); |
| 49 | + } |
| 50 | + |
| 51 | + // OUTPUT |
| 52 | + function outputFinalCss(modifiedCss, options) { |
| 53 | + return css.stringify(modifiedCss, options); |
| 54 | + } |
| 55 | + |
| 56 | + // MAIN |
| 57 | + let transform = function (file, encoding, callback) { |
| 58 | + let parsedCss = parseInputCss(file, encoding, options); |
| 59 | + let modifiedCss = removeCssAttributes(parsedCss, attributesNotToRemove); |
| 60 | + let finalCss = outputFinalCss(modifiedCss, options); |
| 61 | + file.contents = Buffer.from(finalCss); |
| 62 | + |
| 63 | + // success |
| 64 | + callback(null, file); |
| 65 | + }; |
| 66 | + |
| 67 | + // |
| 68 | + return through.obj(transform); |
| 69 | +}; |
0 commit comments