Skip to content

Instantly share code, notes, and snippets.

@ykrods
Created May 1, 2024 08:25
Show Gist options
  • Save ykrods/9817ce0d9abb4796b5441513f88ce187 to your computer and use it in GitHub Desktop.
Save ykrods/9817ce0d9abb4796b5441513f88ce187 to your computer and use it in GitHub Desktop.
/**
* prerender (SSG) with svelte
*
* based on: https://github.com/sssx-dev/sssx
*/
import fs from "node:fs/promises";
import { fileURLToPath } from 'node:url'
import { compile } from "svelte/compiler";
import esbuild from "esbuild";
import sveltePreprocess from "svelte-preprocess";
import sveltePlugin from "esbuild-svelte";
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const template = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Svelte</title>
<!--app-head-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="./main.js"></script>
</body>
</html>`;
(async() => {
const compilerOptions = {
generate: "ssr",
css: "none",
hydratable: true,
};
const svelteCode = `<script>import App from "./App.svelte";</script><App />`;
const result = compile(svelteCode, compilerOptions);
const code = result.js.code
console.log(code)
const es = await esbuild.build({
bundle: true,
minify: false,
format: "esm",
write: false,
splitting: false,
stdin: {
contents: code,
loader: "js",
resolveDir: __dirname + "/src/",
},
plugins: [
sveltePlugin({
preprocess: sveltePreprocess(),
compilerOptions,
}),
]
})
const js = es.outputFiles[0].text
console.log(js)
const dataUri = "data:text/javascript;charset=utf-8," + encodeURIComponent(js);
const App = (await import (dataUri)).default;
const rendered = App.render();
console.log(rendered)
/**
const output = template
.replace('<!--app-head-->', rendered.head ?? '')
.replace('<!--app-html-->', rendered.html ?? '');
await fs.writeFile("./dist/index.html", output, { encoding: "utf-8" });
*/
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment