Tailwind PostCSS inject styles inline instead of generating a CSS file

Viewed 846

I am using PUG + Tailwind + PostCSS for a static, single page HTML file which is generated using basic NPM scripts (shown below)

I would like the final HTML to have the tailwind styles inlined directly in the index.html page, instead of being generated as a .css file which is them referenced in the index.html file.

Instead of using an external file:

link(rel="stylesheet" href="styles.css")

I want this:

<style>
  // all my (tailwind) CSS here
</style>

Obviously the injection has to happen after Pug has compiled and also tailwind has been compiled.

My question is, is there a Tailwind plugin or is a PostCSS-cli plugin/setting?

I have been searching for a few hours without luck.

Here's my NPM scripts:

"start": "npm run build && npm run css",
"build": "pug -O src/data/index.js -P -w src/html/index.pug -o dist",
"css": "postcss -o ./dist/styles.css ./src/css/*.css --watch",
2 Answers

You could always disable the css "cleaning", compile your css independently of the pug and link them together with webpack.

See this question and this webpack plugin.

Hope it helps, for once. At least it would work.

You could simply inject the css file into your html after any build commands, with a script like this:

#!/bin/bash
# inject_css.sh

cp index.html output.html

echo "<style>" >> output.html
cat dist/styles.css >> output.html
echo "</style>" >> output.html

Then, add this script after your build rules in your NPM script like so:

"start": "npm run build && npm run css && ./inject_css.sh"

>> Appends text to a file. In this case, we're adding an opening style tag, then concatenating output.css, then finally, closing the style tag and you should have all your compiled css code directly inside a style tag in your HTML.

Related