docs(bun-plugin-svelte): add example (#18076)

This commit is contained in:
Don Isaac
2025-03-11 14:39:10 -07:00
committed by GitHub
parent 9a5afe371a
commit fdd750e4b5
8 changed files with 483 additions and 41 deletions

View File

@@ -8,7 +8,7 @@ The official [Svelte](https://svelte.dev/) plugin for [Bun](https://bun.sh/).
## Installation
```sh
bun add -D bun-plugin-svelte
$ bun add -D bun-plugin-svelte
```
## Dev Server Usage
@@ -16,52 +16,25 @@ bun add -D bun-plugin-svelte
`bun-plugin-svelte` integrates with Bun's [Fullstack Dev Server](https://bun.sh/docs/bundler/fullstack), giving you
HMR when developing your Svelte app.
```html
<!-- index.html -->
<html>
<head>
<script type="module" src="./index.ts"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
Start by registering it in your [bunfig.toml](https://bun.sh/docs/runtime/bunfig):
```toml
[serve.static]
plugins = ["bun-plugin-svelte"]
```
```ts
// index.ts
Then start your dev server:
import { mount, unmount } from "svelte";
import App from "./App.svelte";
// mount the application entrypoint to the DOM
const root = document.getElementById("root")!;
const app = mount(App, { target: root });
```
$ bun index.html
```
```svelte
<!-- App.svelte -->
<script lang="ts">
// out-of-the-box typescript support
let name: string = "Bun";
</script>
<main class="app">
<h1>Cookin up apps with {name}</h1>
</main>
<style>
h1 {
color: #ff3e00;
text-align: center;
font-size: 2em;
}
</style>
```
See the [example](https://github.com/oven-sh/bun/tree/main/packages/bun-plugin-svelte/example) for a complete example.
## Bundler Usage
`bun-plugin-svelte` lets you bundle Svelte components with [`Bun.build`](https://bun.sh/docs/bundler).
```ts
// build.ts
// to use: bun run build.ts
@@ -70,7 +43,7 @@ import { SveltePlugin } from "bun-plugin-svelte"; // NOTE: not published to npm
Bun.build({
entrypoints: ["src/index.ts"],
outdir: "dist",
target: "browser", // use "bun" or "node" to use Svelte components server-side
target: "browser",
sourcemap: true, // sourcemaps not yet supported
plugins: [
SveltePlugin({

View File

@@ -0,0 +1,311 @@
<script lang="ts">
import FeatureCard from "./FeatureCard.svelte";
const links = [
{ text: "Bun Documentation", url: "https://bun.sh/docs" },
{ text: "Svelte Documentation", url: "https://svelte.dev/docs" },
{ text: "GitHub", url: "https://github.com/oven-sh/bun/tree/main/packages/bun-plugin-svelte" },
];
</script>
<main>
<div class="hero">
<div class="logo-container">
<a href="https://bun.sh" class="bun-logo">
<img
src="https://github.com/user-attachments/assets/50282090-adfd-4ddb-9e27-c30753c6b161"
alt="Bun Logo"
height="42"
/>
</a>
</div>
<h1><span class="highlight">bun-plugin-svelte</span></h1>
<p class="tagline">The official Svelte plugin for <a href="https://bun.sh" target="_blank">Bun</a></p>
<div class="cta-buttons">
<a href="https://bun.sh/docs/bundler/html" class="button primary">🚀 Get Started</a>
<a href="https://github.com/oven-sh/bun/tree/main/packages/bun-plugin-svelte/example" class="button secondary"
>👀 View Examples</a
>
</div>
</div>
<section class="usage">
<h2>🏃‍➡️ Quick Start</h2>
<div class="flex-grid">
<div>
<h3>1. Install from <a href="https://npmjs.com/package/bun-plugin-svelte" target="_blank">NPM</a></h3>
<pre><code class="language-bash">bun add -D bun-plugin-svelte</code></pre>
</div>
<div>
<h3>2. Add it to your <a href="https://bun.sh/docs/runtime/bunfig" target="_blank">bunfig.toml</a></h3>
<pre><code class="language-toml">
[serve.static]
plugins = ["bun-plugin-svelte"];
</code></pre>
</div>
</div>
</section>
<section class="features">
<h2>✨ Features</h2>
<div class="feature-grid">
<FeatureCard title="🔥 HMR Support" link="https://bun.sh/docs/bundler/html">
Integrates with Bun's Fullstack Dev Server for hot module replacement
</FeatureCard>
<FeatureCard title="📦 Bundling" link="https://bun.sh/docs/bundler">
Bundle Svelte components with <a href="https://bun.sh/docs/bundler">Bun.build</a>
</FeatureCard>
</div>
<section class="resources">
<h2>📖 Resources</h2>
<ul class="resource-links">
{#each links as link}
<li><a href={link.url} target="_blank" rel="noopener noreferrer">{link.text}</a></li>
{/each}
</ul>
</section>
<footer>
<p>Made with ❤️ by the Bun team</p>
</footer>
</section>
</main>
<style>
:global(body) {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans",
"Helvetica Neue", sans-serif;
background-color: #f9f9f9;
color: #333;
}
:global(a) {
color: #ff3e00;
text-decoration: none;
position: relative;
}
:global(a::after) {
content: "";
position: absolute;
width: 100%;
height: 1px;
bottom: 0;
left: 0;
background-color: #ff3e00;
transform: scaleX(0);
transform-origin: bottom right;
transition: transform 0.3s ease-out;
}
:global(a:hover::after) {
transform: scaleX(1);
transform-origin: bottom left;
}
:global(a:visited) {
color: #ff3e00;
}
:global(pre > code.hljs) {
padding: 0;
}
main {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
.hero {
text-align: center;
padding: 3rem 1rem;
margin-bottom: 2rem;
display: flex;
flex-direction: column;
}
.logo-container {
margin-bottom: 1.5rem;
margin: auto 25%;
}
.bun-logo {
display: block;
transition: transform 0.3s ease;
}
.bun-logo:hover {
transform: scale(1.05);
}
.bun-logo img {
max-width: 33vw;
height: auto;
}
h1 {
font-size: 2.5rem;
margin-bottom: 0.5rem;
}
.highlight {
color: #ff3e00;
font-weight: bold;
}
/* Don't apply the underline effect to buttons and resource links */
.button::after,
.resource-links li a::after,
.bun-logo::after {
display: none;
}
.tagline {
font-size: 1.2rem;
color: #666;
margin-bottom: 2rem;
}
.cta-buttons {
display: flex;
justify-content: center;
gap: 1rem;
margin-bottom: 2rem;
}
.button {
display: inline-block;
padding: 0.8rem 1.5rem;
border-radius: 4px;
text-decoration: none;
font-weight: 600;
transition: all 0.2s ease;
}
.button.primary {
background-color: #ff3e00;
color: white;
box-shadow: 0 2px 10px rgba(255, 62, 0, 0.2);
}
.button.primary:hover {
background-color: #e63600;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(255, 62, 0, 0.3);
}
.button.secondary {
background-color: #f0f0f0;
color: #333;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.button.secondary:hover {
background-color: #e6e6e6;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
section {
margin-bottom: 3rem;
padding: 2rem;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
}
h2 {
font-size: 1.8rem;
margin-bottom: 1.5rem;
color: #333;
border-bottom: 2px solid #f0f0f0;
padding-bottom: 0.5rem;
}
.flex-grid {
display: flex;
gap: 1.5rem;
}
.flex-grid > div {
flex: 1;
}
.feature-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1.5rem;
margin-bottom: 2rem;
}
pre {
background-color: #f5f5f5;
padding: 1rem;
border-radius: 4px;
overflow-x: auto;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
font-size: 0.9rem;
line-height: 1.5;
}
code {
color: #333;
}
.resource-links {
list-style: none;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.resource-links li a {
display: inline-block;
padding: 0.5rem 1rem;
background-color: #f5f5f5;
color: #333;
text-decoration: none;
border-radius: 4px;
transition: all 0.2s ease;
}
.resource-links li a:hover {
background-color: #ff3e00;
color: white;
transform: translateY(-2px);
}
footer {
text-align: center;
padding: 2rem 0;
color: #666;
font-size: 0.9rem;
}
@media (max-width: 768px) {
.feature-grid {
grid-template-columns: 1fr;
}
.cta-buttons {
flex-direction: column;
align-items: center;
}
.button {
width: 100%;
max-width: 300px;
margin-bottom: 0.5rem;
text-align: center;
}
.resource-links {
flex-direction: column;
}
}
</style>

View File

@@ -0,0 +1,28 @@
<script lang="ts">
let { title, link, children } = $props();
</script>
<div class="feature-card">
<h3>
<a href={link}>
{title}
</a>
</h3>
<p>
{@render children()}
</p>
</div>
<style>
.feature-card {
padding: 1rem;
border-radius: 0.5rem;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.feature-card h3 {
margin-bottom: 0.5rem;
}
</style>

View File

@@ -0,0 +1,2 @@
[serve.static]
plugins = ["bun-plugin-svelte"]

View File

@@ -0,0 +1,25 @@
<html>
<head>
<script type="module" src="./index.ts"></script>
<link rel="prefetch" href="https://bun.sh/docs/bundler/plugins" />
<link rel="preconnect" href="https://bun.sh" />
<link rel="preconnect" href="https://github.com" />
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/default.min.css"
/>
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/languages/toml.min.js"></script>
<script>
hljs.highlightAll();
</script>
</head>
<body>
<div id="root"></div>
</body>
</html>

View File

@@ -0,0 +1,29 @@
import { mount, unmount } from "svelte";
import App from "./App.svelte";
declare global {
var didMount: boolean | undefined;
var hljs: any;
}
let app: Record<string, any> | undefined;
// mount the application entrypoint to the DOM on first load. On subsequent hot
// updates, the app will be unmounted and re-mounted via the accept handler.
const root = document.getElementById("root")!;
if (!globalThis.didMount) {
app = mount(App, { target: root });
}
globalThis.didMount = true;
if (import.meta.hot) {
import.meta.hot.accept(async () => {
// avoid unmounting twice when another update gets accepted while outros are playing
if (!app) return;
const prevApp = app;
app = undefined;
await unmount(prevApp, { outro: true });
app = mount(App, { target: root });
});
}

View File

@@ -1,6 +1,6 @@
{
"name": "bun-plugin-svelte",
"version": "0.0.1",
"version": "0.0.5",
"description": "Official Svelte plugin for Bun",
"repository": {
"type": "git",
@@ -16,7 +16,9 @@
".": "./src/index.ts"
},
"scripts": {
"example": "bun --config=./example/bunfig.toml example/index.html",
"lint": "oxlint .",
"fmt": "prettier --write .",
"check:types": "tsc --noEmit",
"build:types": "tsc --emitDeclarationOnly --declaration --declarationDir ./dist"
},

View File

@@ -0,0 +1,72 @@
import { basename } from "node:path";
import type { BuildConfig, Transpiler } from "bun";
import { getBaseCompileOptions, getBaseModuleCompileOptions, hash, type SvelteOptions } from "./options";
import { compile, type CompileOptions, type CompileResult, type ModuleCompileOptions } from "svelte/compiler";
const virtualNamespace = "bun-svelte";
export class SveltePluginService {
private compileOptions: CompileOptions;
private compileModuleOptions: ModuleCompileOptions;
private ts: Transpiler;
/** Virtual CSS modules created by Svelte components. Keys are import specifiers. */
private css: Map<string, VirtualCSSModule>;
constructor(options: SvelteOptions, config: Partial<BuildConfig>) {
this.compileOptions = getBaseCompileOptions(options, config);
this.compileModuleOptions = getBaseModuleCompileOptions(options, config);
this.ts = new Bun.Transpiler({ loader: "ts" });
this.css = new Map();
}
public compileComponent(source: string, filename: string, hmr: boolean, side?: "client" | "server"): CompileResult {
const generate = this.compileOptions.generate ?? side;
const result = compile(source, {
...this.compileOptions,
generate,
filename,
hmr,
});
var { js, css } = result;
if (css?.code && generate != "server") {
const uid = `${basename(filename)}-${hash(filename)}-style`.replaceAll(`"`, `'`);
const virtualName = virtualNamespace + ":" + uid + ".css";
this.css.set(virtualName, { sourcePath: filename, source: css.code });
js.code += `\nimport "${virtualName}";`;
}
return result;
}
public async compileModule(source: string, filename: string, side?: "client" | "server"): Promise<CompileResult> {
const generate = this.compileModuleOptions.generate ?? side;
if (filename.endsWith("ts")) {
source = await this.ts.transform(source);
}
// NOTE: we assume js/ts modules won't have CSS blocks in them, so no
// virtual modules get created.
return compile(source, {
...this.compileModuleOptions,
generate,
filename,
});
}
public takeVirtualCSSModule(path: string): VirtualCSSModule {
const mod = this.css.get(path);
if (!mod) throw new Error("Virtual CSS module not found: " + path);
this.css.delete(path);
return mod;
}
}
type VirtualCSSModule = {
/** Path to the svelte file whose css this is for */
sourcePath: string;
/** Source code */
source: string;
};