Last active
February 18, 2021 12:23
-
-
Save mizchi/7514eed5fc793e40001716ca2279893c to your computer and use it in GitHub Desktop.
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 * 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