/** * This script generates a custom index.html file for the webview UI. * It reads the manifest.json file generated by Vite and uses it to generate the HTML file. * It also processes the CSS files to rewrite the URLs in the CSS files to match the new location of the assets. * The script is run after the Vite build is complete. * * This is necessary because the webview UI is loaded from the local file system and the URLs in the CSS files need to be rewritten to match the new location of the assets. * The generated index.html file is then used as the entry point for the webview UI. */ import fs from "node:fs"; import postcss from "postcss"; import path from "node:path"; import css_url from "postcss-url"; const distPath = path.resolve("dist"); const manifestPath = path.join(distPath, ".vite/manifest.json"); const outputPath = path.join(distPath, "index.html"); fs.readFile(manifestPath, { encoding: "utf8" }, (err, data) => { if (err) { return console.error("Failed to read manifest:", err); } const manifest = JSON.parse(data); /** @type {{ file: string; name: string; src: string; isEntry: bool; css: string[]; } []} */ const assets = Object.values(manifest); console.log(`Generate custom index.html from ${manifestPath} ...`); // Start with a basic HTML structure let htmlContent = ` Webview UI`; // Add linked stylesheets assets.forEach((asset) => { // console.log(asset); if (asset.src === "index.html") { asset.css.forEach((cssEntry) => { // css to be processed const css = fs.readFileSync(`dist/${cssEntry}`, "utf8"); // process css postcss() .use( css_url({ url: (asset, dir) => { const res = path.basename(asset.url); console.log(`Rewriting CSS url(): ${asset.url} to ${res}`); return res; }, }), ) .process(css, { from: `dist/${cssEntry}`, to: `dist/${cssEntry}`, }) .then((result) => { fs.writeFileSync(`dist/${cssEntry}`, result.css, "utf8"); }); // Extend the HTML content with the linked stylesheet console.log(`Relinking html css stylesheet: ${cssEntry}`); htmlContent += `\n `; }); } }); htmlContent += `
`; // Add scripts assets.forEach((asset) => { if (asset.file.endsWith(".js")) { console.log(`Relinking js script: ${asset.file}`); htmlContent += `\n `; } }); htmlContent += ` `; // Write the HTML file fs.writeFile(outputPath, htmlContent, (err) => { if (err) { console.error("Failed to write custom index.html:", err); } else { console.log("Custom index.html generated successfully!"); } }); });