1

i wan to create new css with lowest and highest value.

     table[my-type="myStyle"] {
        width: 255.388px !important;
    }

and the above code present in n number of css files in my style directory.

1 Answer 1

2

You can use postcss to parse the css and get the values you want.

Here is an example of how to get min and max width from different css files (for the same selector table[my-type="myStyle"]):

const fs = require('fs');
const postcss = require('postcss');

const allWidthValues = [];

const files = [
    'styles/style-1.css',
    'styles/style-2.css',
    'styles/style-3.css'
];

const selector = 'table[my-type="myStyle"]';

const processor = postcss.plugin('processor', () => (css) => {    
    // Callback for each rule node.
    css.walkRules((rule) => {        
        // Match the individual rule selector 
        if (rule.selector.indexOf(selector) !== -1) {
            // Callback for each declaration.
            rule.walkDecls(decl => {
                // Find the width declaration
                if(decl.prop.indexOf('width') !== -1) {
                    const width = decl.value.replace('px', '') * 1;
                    allWidthValues.push(width);
                }
            })
        }
    });
});

files.forEach(file => {
    const css = fs.readFileSync(file, 'utf-8');
    postcss([processor])
        .process(css, {from : file})
        .then(() => console.log('Done processing file : ', file))
        .catch(() => console.log('Error processing file : ', file));    

});

console.log('All width values : ', allWidthValues);

allWidthValues.sort();

console.log('Min width : ', allWidthValues[0]);
console.log('Max width : ', allWidthValues[allWidthValues.length - 1]);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks MohamedRamrami, Is there any way to avoid this, const files = [ 'styles/style-1.css', 'styles/style-2.css', 'styles/style-3.css' ]; ie, can we get the files list from style directory by automated ?
Yes, you can use the npm package glob, like this const files = glob.sync('./styles/*.css');
That will return all css files in the styles directory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.