Skip to content

Instantly share code, notes, and snippets.

@devwax
Forked from farolanf/inline-styles.mjs
Last active May 17, 2023 01:05
Show Gist options
  • Save devwax/f24152349d66ead2c984e3d432af26d4 to your computer and use it in GitHub Desktop.
Save devwax/f24152349d66ead2c984e3d432af26d4 to your computer and use it in GitHub Desktop.
Astro JS - Inline CSS
import path from 'node:path'
import fs from 'node:fs/promises'
import { globby } from 'globby'
const files = await globby('./dist/**/index.html')
await Promise.all(
files.map(async (htmlPath) => {
const pageStyles = []
const stylesPaths = []
let file = await fs.readFile(htmlPath, 'utf-8')
file = file.replace(
/<link rel="stylesheet" href="(.*?)"\s*\/?>/g,
(match, p1) => {
// console.log('p1', p1);
stylesPaths.push(p1)
return `{{${p1}}}`
}
)
await Promise.all(
stylesPaths.map(async (stylesPathRaw) => {
let stylesPath = stylesPathRaw
stylesPath = path.resolve('./dist' + stylesPath)
console.log('stylesPath', stylesPath);
const styles = await fs.readFile(stylesPath, 'utf-8')
pageStyles.push(styles)
})
)
stylesPaths.forEach((p, i) => {
file = file.replace(`{{${p}}}`, `<style>${pageStyles[i]}</style>`)
})
await fs.writeFile(htmlPath, file)
})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment