csstools/precss

how to do tailwindcss-like @apply to extend rules

muayyad-alsadi opened this issue · 1 comments

hi

is there a way to do something like this

.px_s {padding-left: 8px; padding-right: 8px;}
.py_xs {padding-left: 4px; padding-right: 4px;}
.bg_primary {background-color: #acf;}

.btn {
@apply .px_s .py_xs .bg_primary
}

because with @mixin from postcss-advanced-variables
I have to define small padding on x twice, once as a class rule '.px_s' and once as a mixing

I've learned how

const postcss = require('postcss');

module.exports = function(options = {}) {
    return {
        postcssPlugin: 'postcss-apply-rules',
        AtRule: {
            'apply': function(atRule) {
                const root = atRule.root();
                const parent = atRule.parent;
                // @apply sel1 sel2 sel3
                const refs = atRule.params.split(/\s+/g).map(i=>i.trim()).filter(i=>i);
                for(const sel of refs) {
                    root.walkRules(sel, function(role) {
                        role.walkDecls(decl=>parent.insertBefore(atRule, decl.clone()));
                    });
                }
                atRule.remove();
            }
        },
    }
};

module.exports.postcss = true