Skip to content

Use Tailwind to extract actual CSS rules (instead of interpreting TW classes with a cheatsheet) #47

@ADTC

Description

@ADTC

Update: Happy to announce we have a fully working Tailwind-to-CSS converter that's server-based and doesn't depend on cheatsheets here: https://tailwind-to-css-three.vercel.app/

Source code is here: https://github.com/ADTC/tailwind_to_css


Previous Update: I made a version that does this: https://tailwind-to-css-three.vercel.app/


I think the best way to get the CSS would be to actually apply the Tailwind classes to a <div> element, and then extract the rules like this:

// Function to get applied CSS rules
function getAppliedCSSRules(element) {
  const stylesheets = Array.from(document.styleSheets);
  const appliedRules = [];

  stylesheets.forEach(sheet => {
    try {
      const rules = Array.from(sheet.cssRules);

      rules.forEach(rule => {
        if (rule.type === CSSRule.STYLE_RULE && element.matches(rule.selectorText)) {
          let css = rule.cssText;
          if (!css.startsWith('.')) return;
          css = css.substring(css.indexOf('{') + 1, css.lastIndexOf('}')).trim();
          css = css.replace(/; /g, ';\n');
          appliedRules.push(css);
        }
      });
    } catch (e) {
      console.warn('Access to stylesheet is restricted:', sheet.href);
    }
  });

  return appliedRules;
}

// Create the element
const element = document.createElement('DIV');
document.body.appendChild(element);

// Apply the Tailwind classes
element.className = input;

// Get applied CSS rules
const appliedRules = getAppliedCSSRules(element);
const concatenatedRules = appliedRules.join('\n');

// Remove the element
element.remove();
console.log(concatenatedRules); // or return the string

It will be far superior because you no longer need to have an up-to-date cheat sheet, and it will work with crazy TW classes like the ones in #45.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions