Created
February 19, 2022 11:36
-
-
Save Igloczek/2e8f5596490bc56eda1486e5ed8f4a07 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="(.*?)">/g, | |
(match, p1) => { | |
stylesPaths.push(p1) | |
return '' | |
} | |
) | |
await Promise.all( | |
stylesPaths.map(async stylesPath => { | |
const styles = await fs.readFile(path.resolve(path.dirname(htmlPath), stylesPath), 'utf-8') | |
pageStyles.push(styles) | |
}) | |
) | |
file = file.replace( | |
'<meta charset="UTF-8">', | |
`<style>${pageStyles.join(' ')}</style>\n<meta charset="UTF-8">` | |
) | |
await fs.writeFile(htmlPath, file) | |
}) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Modified to keep styles ordering https://gist.github.com/farolanf/9f62978f654a2e282c60be9e12422ba2