SvelteKit
Svelte-based full-stack framework. Also provides SSG mode with over 17k GitHub stars as lightweight fast framework.
トレンド・動向
Gaining attention as SSG leveraging Svelte's lightweight nature and performance. Generates fast sites through compile-time optimization.
# Static Site Generator
SvelteKit
## Overview
SvelteKit is a Svelte-based full-stack framework that also provides powerful SSG capabilities. With over 17k GitHub stars, this lightweight fast framework leverages Svelte's lightweight nature and performance for SSG applications. It generates fast sites through compile-time optimization.
## Details
SvelteKit development began in 2020 as a next-generation framework adopting a different approach from traditional JavaScript frameworks. Through Svelte's compile-time optimization, it minimizes runtime overhead and can generate extremely fast sites.
### Key Features
#### 1. Flexible Rendering Modes
- **Static Generation (SSG)**: Pre-render all pages at build time using `adapter-static`
- **Server-Side Rendering (SSR)**: Dynamic server rendering
- **Single Page Application (SPA)**: Client-side only rendering
- **Prerendering**: Selective page pre-rendering
#### 2. Svelte-Powered Lightweight Design
- **Compile-time Optimization**: Remove framework code at build time
- **Zero Runtime**: Minimal JavaScript bundle
- **File-based Routing**: Intuitive directory-based routing
- **TypeScript Integration**: First-class TypeScript support
#### 3. Performance-Focused Design
- **Fast Builds**: Efficient build process
- **Minimal Bundle Size**: Automatic removal of unnecessary code
- **Preload Strategy**: Intelligent code preloading
- **SEO Optimization**: Built-in meta tags and SEO support
#### 4. Developer Experience
- **Hot Reload**: Fast change reflection in development environment
- **Type Safety**: Auto-generated type definitions
- **Error Handling**: Clear error messages
- **Debug Tools**: Integrated debugging capabilities
## Pros and Cons
### Pros
- **Lightweight**: Extremely lightweight bundle size due to Svelte characteristics
- **High Performance**: High runtime performance through compile-time optimization
- **Low Learning Curve**: Simple syntax and file-based routing
- **Flexibility**: Multiple rendering modes and adapter support
- **TypeScript Integration**: Excellent TypeScript development experience
- **SEO-friendly**: Search engine optimization through static generation
### Cons
- **Ecosystem**: Fewer libraries compared to React or Vue
- **Community Size**: Smaller community
- **Enterprise Adoption**: Limited adoption cases in large enterprises
- **Learning Resources**: Relatively fewer documentation and learning materials
## Reference Pages
- [Official Website](https://kit.svelte.dev/)
- [Svelte Documentation](https://svelte.dev/docs)
- [GitHub Repository](https://github.com/sveltejs/kit)
- [Adapters List](https://kit.svelte.dev/docs/adapters)
- [Tutorial](https://learn.svelte.dev/)
## Code Examples
### 1. Installation and Setup
**Creating a SvelteKit Project**
```bash
# Create a new SvelteKit project
npm create svelte@latest my-sveltekit-app
cd my-sveltekit-app
# Install dependencies
npm install
# Start development server
npm run dev
```
**svelte.config.js for SSG**
```javascript
import adapter from '@sveltejs/adapter-static';
export default {
kit: {
adapter: adapter({
// Output directory settings
pages: 'build',
assets: 'build',
fallback: undefined,
precompress: false,
strict: true
}),
paths: {
base: process.env.NODE_ENV === 'production' ? '/my-site' : ''
}
}
};
```
### 2. Pages and Routing
**src/routes/+page.svelte**
```svelte
<script>
// Page metadata
import { page } from '$app/stores';
export let data;
</script>
<svelte:head>
<title>Homepage - SvelteKit Site</title>
<meta name="description" content="Static site built with SvelteKit" />
</svelte:head>
<main>
<h1>Welcome to SvelteKit Site</h1>
<p>Fast and lightweight static site.</p>
<a href="/blog">View Blog</a>
</main>
<style>
main {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
h1 {
color: #ff3e00;
text-align: center;
}
</style>
```
**src/routes/+layout.js**
```javascript
// Enable prerendering for all pages
export const prerender = true;
```
### 3. Dynamic Routes and Data Fetching
**src/routes/blog/[slug]/+page.js**
```javascript
import { error } from '@sveltejs/kit';
/** @type {import('./$types').PageLoad} */
export async function load({ params }) {
try {
const post = await import(`../../../posts/${params.slug}.md`);
return {
content: post.default,
meta: post.metadata
};
} catch (e) {
throw error(404, `Post not found: ${params.slug}`);
}
}
// Dynamic route prerendering configuration
export const prerender = true;
/** @type {import('./$types').EntryGenerator} */
export function entries() {
return [
{ slug: 'first-post' },
{ slug: 'second-post' },
{ slug: 'third-post' }
];
}
```
**src/routes/blog/[slug]/+page.svelte**
```svelte
<script>
export let data;
</script>
<svelte:head>
<title>{data.meta.title} - Blog</title>
<meta name="description" content={data.meta.description} />
</svelte:head>
<article>
<header>
<h1>{data.meta.title}</h1>
<time datetime={data.meta.date}>{data.meta.date}</time>
</header>
<div class="content">
<svelte:component this={data.content} />
</div>
</article>
<style>
article {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
header {
margin-bottom: 2rem;
border-bottom: 1px solid #eee;
padding-bottom: 1rem;
}
.content {
line-height: 1.6;
}
</style>
```
### 4. State Management
**src/lib/stores.js**
```javascript
import { writable } from 'svelte/store';
// Theme management
export const theme = writable('light');
// User settings
export const userSettings = writable({
language: 'en',
notifications: true
});
// Counter example
export const count = writable(0);
```
**src/routes/settings/+page.svelte**
```svelte
<script>
import { theme, userSettings } from '$lib/stores.js';
function toggleTheme() {
theme.update(t => t === 'light' ? 'dark' : 'light');
}
</script>
<main>
<h1>Settings</h1>
<section>
<h2>Appearance</h2>
<label>
<input type="radio" bind:group={$theme} value="light" />
Light Theme
</label>
<label>
<input type="radio" bind:group={$theme} value="dark" />
Dark Theme
</label>
</section>
<section>
<h2>Language Settings</h2>
<select bind:value={$userSettings.language}>
<option value="en">English</option>
<option value="ja">Japanese</option>
</select>
</section>
</main>
```
### 5. Form Handling
**src/routes/contact/+page.server.js**
```javascript
import { fail } from '@sveltejs/kit';
/** @type {import('./$types').Actions} */
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
const name = data.get('name');
const email = data.get('email');
const message = data.get('message');
// Validation
if (!name || !email || !message) {
return fail(400, {
error: 'Please fill in all fields',
name,
email,
message
});
}
// Email sending process (implementation omitted)
console.log('Contact received:', { name, email, message });
return {
success: true
};
}
};
```
**src/routes/contact/+page.svelte**
```svelte
<script>
import { enhance } from '$app/forms';
export let form;
</script>
<svelte:head>
<title>Contact</title>
</svelte:head>
<main>
<h1>Contact Us</h1>
{#if form?.success}
<div class="success">
Thank you for your message!
</div>
{/if}
{#if form?.error}
<div class="error">
{form.error}
</div>
{/if}
<form method="POST" use:enhance>
<label>
Name
<input type="text" name="name" value={form?.name ?? ''} required />
</label>
<label>
Email
<input type="email" name="email" value={form?.email ?? ''} required />
</label>
<label>
Message
<textarea name="message" required>{form?.message ?? ''}</textarea>
</label>
<button type="submit">Send</button>
</form>
</main>
<style>
form {
max-width: 500px;
margin: 0 auto;
}
label {
display: block;
margin-bottom: 1rem;
}
input, textarea {
width: 100%;
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background: #ff3e00;
color: white;
padding: 0.75rem 1.5rem;
border: none;
border-radius: 4px;
cursor: pointer;
}
.success {
background: #d4edda;
color: #155724;
padding: 1rem;
border-radius: 4px;
margin-bottom: 1rem;
}
.error {
background: #f8d7da;
color: #721c24;
padding: 1rem;
border-radius: 4px;
margin-bottom: 1rem;
}
</style>
```
### 6. Deployment and Build
**Building Static Site**
```bash
# Generate static site
npm run build
# Preview locally
npm run preview
```
**package.json Scripts Example**
```json
{
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
}
}
```
**GitHub Pages Deployment Configuration**
```javascript
// svelte.config.js
import adapter from '@sveltejs/adapter-static';
const dev = process.argv.includes('dev');
export default {
kit: {
adapter: adapter({
fallback: '404.html'
}),
paths: {
base: dev ? '' : process.env.BASE_PATH
}
}
};
```