Skip to content

Instantly share code, notes, and snippets.

@rdmurphy
Created May 28, 2020 03:45
Show Gist options
  • Save rdmurphy/4b89ef4dcccd30ddb9bbe972efafcd96 to your computer and use it in GitHub Desktop.
Save rdmurphy/4b89ef4dcccd30ddb9bbe972efafcd96 to your computer and use it in GitHub Desktop.
// packages
const rollup = require('rollup');
const svelte = require('rollup-plugin-svelte');
const { nodeResolve } = require('@rollup/plugin-node-resolve');
const sucrase = require('@rollup/plugin-sucrase');
const requireFromString = require('require-from-string');
const defaultInputOptions = {
plugins: [
svelte({ generate: 'ssr', hydratable: true }),
nodeResolve(),
sucrase({ transforms: ['typescript'] }),
],
};
const outputOptions = { format: 'commonjs' };
async function compileSvelteComponent(input) {
// prepare the bundle
const bundle = await rollup.rollup({ input, ...defaultInputOptions });
// generate our output
const { output } = await bundle.generate(outputOptions);
// we only care about our singular bundle and its code
const code = output[0].code;
// prep our rendered Component
const Component = requireFromString(code);
// it is ready
return Component;
}
(async () => {
// it's ready to go
const HelloWorld = await compileSvelteComponent('HelloWorld.svelte');
console.log(HelloWorld.render().html);
console.log(HelloWorld.render({ name: 'Will' }).html);
})();
<script>
import Paragraph from "./Paragraph.svelte";
export let name = "Abe";
</script>
<h1>Hello, {name}!</h1>
<Paragraph />
export function square(n: number): number {
return n * n;
}
{
"private": true,
"dependencies": {
"@rollup/plugin-node-resolve": "^8.0.0",
"@rollup/plugin-sucrase": "^3.0.2",
"journalize": "^2.4.0",
"require-from-string": "^2.0.2",
"rollup": "^2.11.0",
"rollup-plugin-svelte": "^5.2.2",
"svelte": "^3.23.0"
}
}
<script>
import { intcomma } from "journalize";
import { square } from "./math.ts";
let n = 5;
</script>
<p>I am a paragraph! This is a number: {intcomma(5432)}</p>
<p>The number {n} squared is {square(n)}.</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment