Gregor Voinov
Gregor Voinov

Reputation: 2263

Convert tailwindcss classes to vanilla css

is there any lib that can take a dom element and return a string with vanilla css, to use inside a webproject?

const styles = TailwindToStyles('<div class="bg-teal-100 m-10">Lorem ipsum</div> ')

result of styles is

.bg-teall-100 {
  background-color: #e6fffa;
}
.m-10{
  margin: 40px
}

gregor

Upvotes: 1

Views: 12373

Answers (3)

Thong Doan
Thong Doan

Reputation: 207

You can try go to tests folder of tailwindcss project(https://github.com/tailwindlabs/tailwindcss/tree/master/tests) to see how it work, or you can try create a helper class:

import config from './tailwind.config';
import resolveConfig from 'tailwindcss/resolveConfig';
const { generateRules } = require('tailwindcss/lib/lib/generateRules');
const { createContext } = require('tailwindcss/lib/lib/setupContextUtils');

export function createTailwindHelper() {
  const context = createContext(resolveConfig(config));

  function sortClasses(classes: string[]): string[] {
    return defaultSort(context.getClassOrder(classes));
  }

  return {
    classesToCss(classes: Set<string>): string | undefined {
      const sortedClasses = sortClasses(Array.from(classes.values()));
      const rules = generateRules(sortedClasses, context);
      if (!rules.length) return;
      const css = rules.map((rule: any) => rule[1].toString()).join('\n');
      if (css) return css;
    },
  };
}

function defaultSort(arrayOfTuples: [string, bigint][]) {
  return arrayOfTuples
    .sort(([, a], [, z]) => {
      if (a === z) return 0;
      if (a === null) return -1;
      if (z === null) return 1;
      return bigSign(a - z);
    })
    .map(([className]) => className);
}

function bigSign(bigIntValue: bigint) {
  // @ts-ignore
  return (bigIntValue > 0n) - (bigIntValue < 0n);
}

Then

function play() {
  const html = `<div class="my-2 bg-teal-100 m-10 my-2">Lorem ipsum</div>`;
  const classes = getAllClassesFromHTML(html);
  const tw = createTailwindHelper();
  const css = tw.classesToCss(classes);

  console.log(css);
}

function getAllClassesFromHTML(htmlString: string): Set<string> {
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlString, 'text/html');

  const allClasses = new Set<string>();
  // Get all HTML elements with classes
  const elementsWithClasses = doc.querySelectorAll('[class]');

  // Iterate through the elements and extract classes
  elementsWithClasses.forEach((element) => {
    const classNames = element.classList;
    classNames.forEach((className) => {
      allClasses.add(className);
    });
  });

  return allClasses;
}

Output (Tailwind 3.3.3)

.m-10 {
    margin: 2.5rem
}
.my-2 {
    margin-top: 0.5rem;
    margin-bottom: 0.5rem
}
.bg-teal-100 {
    --tw-bg-opacity: 1;
    background-color: rgb(204 251 241 / var(--tw-bg-opacity))
}

-----If you want to run it in browser------

In package.json (fix: "Can't resolve 'fs' module"):

"browser": {
    "fs": false
}

In your tailwind config file (fix: "Can't resolve path.join):

module.exports = {
   ...
   corePlugins: {
       preflight: false,
   },
   ...
}

Upvotes: 0

Kromate
Kromate

Reputation: 61

I had a similar problem and solved it by

  • firstly create an Iframe
  • mount the tailwind CDN and then insert the html string to the body
  • extract the generated styles from the head and use.

I released a npm package that does this, check it out here https://www.npmjs.com/package/tailwind-to-css

Upvotes: 4

Solar
Solar

Reputation: 1015

I was looking for a similar tool that can convert the tailwind class to CSS. I ran into one Reddit Thread. There are various tools listed out there.

The one that is simpler and closer to what I was looking for is this app to convert the tailwind class to CSS.

Here is the GitHub link: https://github.com/Devzstudio/tailwind_to_css
Live demo: https://tailwind-to-css.vercel.app/

FOR REACT NATIVE

Thanks to this packet it is possible to copy the entire tailwind code from react project and paste it as a param of the function tailwind() which returns a react-native stylesheet object.

Here's the doc : https://github.com/vadimdemedes/tailwind-rn

Upvotes: 8

Related Questions