-
-
Save farolanf/9f62978f654a2e282c60be9e12422ba2 to your computer and use it in GitHub Desktop.
Astro JS - Inline CSS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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