Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active February 18, 2021 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/7514eed5fc793e40001716ca2279893c to your computer and use it in GitHub Desktop.
Save mizchi/7514eed5fc793e40001716ca2279893c to your computer and use it in GitHub Desktop.
import * as uniroll from "uniroll";
import ts from "typescript";
import { svelte } from "rollup-plugin-uniroll-svelte";
import fetch from "isomorphic-unfetch";
import vm from "vm";
global.fetch = fetch;
const App = `
<script lang="ts">
export let foo: string;
let n = 0;
const onClick = () => {
n = n + 1
}
</script>
<button on:click={onClick}>{foo}{n}</button>
`;
const resolveIdFallback = (id: string) => {
if (id === "svelte/internal") {
return "https://esm.sh/svelte/internal";
}
if (id.startsWith(".")) return;
};
async function main() {
const bundled = await uniroll.bundle({
input: "/index.ts",
extraPlugins: [
svelte({
target: ts.ScriptTarget.Latest,
resolveIdFallback,
svelteOptions: {
hydratable: true,
generate: "ssr",
},
}),
],
files: {
"/App.svelte": App,
"/index.ts": `
import App from './App.svelte';
// out.constructor.prototype.x = 1;
Object.prototype.x = 1;
out = App.render({foo: 'hello'});
`,
},
});
const out = await bundled.generate({ format: "iife" });
const code = out.output[0].code;
const sandbox: any = { out: Object.create(null) };
vm.runInNewContext(code, sandbox);
// @ts-ignore
console.assert({}.x !== 1);
const html: string = sandbox.out.html;
const bundled2 = await uniroll.bundle({
input: "/index.ts",
extraPlugins: [
svelte({
target: ts.ScriptTarget.Latest,
resolveIdFallback,
svelteOptions: {
hydratable: true,
generate: "dom",
},
}),
],
files: {
"/App.svelte": App,
"/index.ts": `
import App from './App.svelte';
new App({
target: document.querySelector("main"),
hydrate: true,
props: { foo: "hello" }
});
`,
},
});
const out2 = await bundled2.generate({ format: "iife" });
const code2 = out2.output[0].code;
console.log(`<html>
<head></head>
<body>
<button onclick="hydrate()">hydrate</button>
<main>${html}</main>
<script>
function hydrate() {
/*<!--*/
${code2}
/*-->*/
}
</script>
</body>
</html>`);
// out.output[0].code
}
main().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment