Created
May 3, 2022 04:04
-
-
Save leaysgur/4e26b6bcdd57dc6e2028215cfffc16f8 to your computer and use it in GitHub Desktop.
Work around for https://github.com/withastro/astro/issues/2146
This file contains hidden or 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
// @ts-check | |
import fs from "node:fs/promises"; | |
import path from "node:path"; | |
// This script is temporary work-around for issue, | |
// https://github.com/withastro/astro/issues/2146 | |
// TL;DR, we need to replace all url() in CSS manually... | |
// e.g. url(__VITE_ASSET__********__) => url(/assets/asset.********.webp) | |
// Some url() work fine if they are updated to data-url. | |
(async () => { | |
const ASSETS_DIR = path.resolve("./dist/assets"); | |
const REPLACE_TARGET_RE = /__VITE_ASSET__([0-9a-f]{8})__/g; | |
console.log("🔄 Checking VITE_ASSET urls in CSS"); | |
const assetPaths = await fs.readdir(ASSETS_DIR); | |
const cssPaths = []; | |
const assetMap = new Map(); | |
for (const assetPath of assetPaths) { | |
if (assetPath.endsWith(".css")) { | |
cssPaths.push(assetPath); | |
} else { | |
const [_, hash] = assetPath.split("."); | |
assetMap.set(hash, assetPath); | |
} | |
} | |
/** @type {string[]} */ | |
const cssPathsToReplace = []; | |
await Promise.all( | |
cssPaths.map((p) => | |
fs.readFile(`${ASSETS_DIR}/${p}`, "utf8").then((c) => { | |
if (REPLACE_TARGET_RE.test(c)) cssPathsToReplace.push(p); | |
}) | |
) | |
); | |
if (cssPathsToReplace.length === 0) { | |
console.log("✅ No files to be replaced!"); | |
return process.exit(0); | |
} | |
for (const css of cssPathsToReplace) { | |
const cssPath = `${ASSETS_DIR}/${css}`; | |
let content = await fs.readFile(cssPath, "utf8"); | |
const matches = content.matchAll(REPLACE_TARGET_RE); | |
// @ts-ignore: downlevelIteration...? | |
for (const match of matches) { | |
const [target, hash] = match; | |
content = content.replace(target, `/assets/${assetMap.get(hash)}`); | |
} | |
await fs.writeFile(cssPath, content, "utf8"); | |
console.log(`✅ Found and replaced ${css}`); | |
} | |
})(); |
Author
leaysgur
commented
May 3, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment