Skip to content

Instantly share code, notes, and snippets.

@farolanf
Forked from Igloczek/inline-styles.mjs
Last active May 17, 2023 01:04
Show Gist options
  • Save farolanf/9f62978f654a2e282c60be9e12422ba2 to your computer and use it in GitHub Desktop.
Save farolanf/9f62978f654a2e282c60be9e12422ba2 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) => {
stylesPaths.push(p1)
return `{{${p1}}}`
}
)
await Promise.all(
stylesPaths.map(async (stylesPath) => {
stylesPath = path.resolve(path.join(path.dirname(htmlPath), 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