How can I build TailwindCSS from an HTML string? I tried:
import postcss from 'postcss'
import tailwindcss from '@tailwindcss/postcss'
export async function buildTailwind(content, css = '') {
const inputCSS = `
@tailwind base;
@tailwind components;
@tailwind utilities;
${css}
`
const result = await postcss([
tailwindcss({
content: [{ raw: content, extension: 'html' }]
})
]).process(inputCSS, { from: undefined })
return result.css
}
await buildTailwind('<p class="text-red-500">Hello, World!</p>')
But I received:
/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */
I want to build a TailwindCSS from an HTML string, preferably without using npx
or cli stuff.
Your example works with TailwindCSS v3.
npm remove @tailwindcss/postcss
npm install tailwindcss@3 postcss
./tailwindcss/compile.js
import postcss from 'postcss'
import tailwindcss from 'tailwindcss'
export async function compileFrom(html, css = '') {
css = `
@tailwind base;
@tailwind components;
@tailwind utilities;
${css}
`
const { css: generated } = await postcss([
tailwindcss({
content: [{ raw: html, extension: 'html' }],
theme: {
extend: {},
},
plugins: [],
})
]).process(inputCSS, { from: undefined })
return generated
}
./index.js
import { compileFrom } from './tailwindcss/compile.js'
const input = `
<p class="text-sky-500">Hello, World!</p>
`
const output = await compileFrom(input)
console.log(output)
Note: Don't forget to set the type attribute to module in your package.json
for ES6 import support.
Related:
However, the content
property has been removed, so you can no longer pass raw HTML. In v4, you need to build a custom solution using internal functions of the engine. If you want to compile generated CSS from a raw string without using files.
As an alternative, you can save the string to a file on the server, then use a server-side script to compile the generated CSS, which you can then send to the client.
Related: