### Create First Vitto Page (Vento Syntax)
Source: https://github.com/riipandi/vitto/blob/main/docs/02-getting-started.md
An example of a basic page template (`index.vto`) using Vento syntax. It demonstrates layout inclusion, metadata setting, and basic HTML structure with dynamic content placeholders.
```vento
{{ layout "layouts/site.vto" }}
{{ setMetadata('title', 'Homepage') }}
{{ title }}
{{ description }}
```
--------------------------------
### Firebase Hosting Setup and Configuration (Bash & JSON)
Source: https://github.com/riipandi/vitto/blob/main/docs/08-deployment.md
Guides through setting up and configuring Firebase Hosting for static site deployments. Includes commands for installing the Firebase CLI, logging in, initializing hosting, and the JSON configuration file for deployment settings.
```bash
# Install Firebase CLI
npm install -g firebase-tools
# Login
firebase login
# Initialize
firebase init hosting
```
```json
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
```
```bash
firebase deploy
```
--------------------------------
### Run Vitto Development Server (NPM, PNPM, Yarn, Bun)
Source: https://github.com/riipandi/vitto/blob/main/docs/02-getting-started.md
Starts the Vitto development server using various package managers. This command builds the site and serves it locally, typically at `http://localhost:5173`, allowing for live preview during development.
```bash
# Using npm
npm run dev
```
```bash
# Using pnpm
pnpm dev
```
```bash
# Using yarn
yarn dev
```
```bash
# Using bun
bun dev
```
--------------------------------
### Scaffold Vitto Project with Template (NPM, Yarn, PNPM, Bun, Deno)
Source: https://github.com/riipandi/vitto/blob/main/docs/02-getting-started.md
Creates a new Vitto project with a specified name and template. This allows for pre-configured setups like Tailwind CSS. The `--template` flag is used to select the desired starter template.
```bash
# npm 7+ (extra double-dash is needed)
npm create vitto@latest my-website -- --template tailwindcss
```
```bash
yarn create vitto my-website --template tailwindcss
```
```bash
pnpm create vitto my-website --template tailwindcss
```
```bash
bun create vitto my-website --template tailwindcss
```
```bash
deno init --npm vitto my-website --template tailwindcss
```
--------------------------------
### Vento Partial Example and Inclusion
Source: https://github.com/riipandi/vitto/blob/main/docs/04-templating.md
Shows how to create and include reusable partials in Vento. `header.vto` is a simple example, and the `include` directive is used to embed it. It also demonstrates passing data to partials.
```vento
```
```vento
{{ include "partials/header.vto" }}
```
```vento
{{ include "partials/card.vto" { title: "Hello", content: "World" } }}
```
```vento
{{ title }}
{{ content }}
```
--------------------------------
### Create New Vitto Project (NPM, Yarn, PNPM, Bun, Deno)
Source: https://github.com/riipandi/vitto/blob/main/docs/02-getting-started.md
Initiates a new Vitto project using the create-vitto scaffolding tool. This command prompts for configuration and sets up the basic project structure. It supports multiple package managers for flexibility.
```bash
npm create vitto@latest
```
```bash
yarn create vitto
```
```bash
pnpm create vitto
```
```bash
bun create vitto
```
```bash
deno init --npm vitto
```
--------------------------------
### Example Pagefind Search Configuration
Source: https://github.com/riipandi/vitto/blob/main/docs/12-api-reference.md
Provides an example configuration for Pagefind search. This setup specifies that only the 'main' content should be indexed, excludes navigation, footers, sidebars, and comments, forces the language to 'en', and enables verbose logging.
```typescript
{
rootSelector: 'main',
excludeSelectors: ['nav', 'footer', '.sidebar', '.comments'],
forceLanguage: 'en',
verbose: true,
keepIndexUrl: true
}
```
--------------------------------
### Build Vitto Project for Production (NPM, PNPM, Yarn, Bun)
Source: https://github.com/riipandi/vitto/blob/main/docs/02-getting-started.md
Builds the Vitto project for production, generating static HTML files in the `dist/` directory. This command optimizes the site for deployment and can be executed using different package managers.
```bash
# Using npm
npm run build
```
```bash
# Using pnpm
pnpm build
```
```bash
# Using yarn
yarn build
```
```bash
# Using bun
bun run build
```
--------------------------------
### Vitto Library Integration Example (Vento/HTML)
Source: https://github.com/riipandi/vitto/blob/main/docs/14-comparison.md
An example of integrating libraries like HTMX into a Vitto project using Vento templating. It shows how to include assets and scripts, either via CDN for quick setup or through Vite bundling.
```vento
{{/* Add any library easily */}}
{{ renderAssets() |> safe }}
{{/* Via CDN for quick setup */}}
{{/* Or via Vite bundler (imported in main.ts) */}}
```
--------------------------------
### Install Vitto Manually (PNPM, NPM, Yarn)
Source: https://github.com/riipandi/vitto/blob/main/docs/02-getting-started.md
Adds Vitto as a development dependency to an existing Vite project. This is useful for integrating Vitto's static site generation capabilities into a project that already uses Vite.
```bash
# Using pnpm
pnpm add -D vitto
```
```bash
# Using npm
npm install --save-dev vitto
```
```bash
# Using yarn
yarn add --dev vitto
```
--------------------------------
### Vento Base Layout Example
Source: https://github.com/riipandi/vitto/blob/main/docs/04-templating.md
An example of a base layout file (`base.vto`) in Vento. It includes essential HTML structure, metadata, header, footer, and renders page content using the `content` variable and `safe` filter.
```vento
{{ set pageTitle = metadata.title ? `${metadata.title} - ${metadata.siteName}` : metadata.siteName }}
{{ pageTitle |> safe }}
{{ renderAssets() |> safe }}
{{ include "partials/header.vto" }}
{{ content |> safe }}
{{ include "partials/footer.vto" }}
```
--------------------------------
### Create Vitto Layout Template (Vento Syntax)
Source: https://github.com/riipandi/vitto/blob/main/docs/02-getting-started.md
A sample layout template (`base.vto`) in Vento syntax. It defines the basic HTML structure, including head and body, and uses Vento directives to render page titles, assets, and content dynamically.
```vento
{{ set pageTitle = metadata.title ? `${metadata.title} - ${metadata.siteName}` : metadata.siteName }}
{{ pageTitle |> safe }}
{{ renderAssets() |> safe }}
{{ content }}
```
--------------------------------
### Vitto HTML Setup with CDN Libraries
Source: https://github.com/riipandi/vitto/blob/main/docs/14-comparison.md
This HTML snippet illustrates how to set up a Vitto project using Content Delivery Network (CDN) links for Tailwind CSS, HTMX, and Alpine.js. This method is useful for quick prototyping or when external dependencies are preferred over local installations.
```html
{{ renderAssets() |> safe }}
{{/* Your content */}}
```
--------------------------------
### Build and Preview Project Locally
Source: https://github.com/riipandi/vitto/blob/main/docs/08-deployment.md
Commands to build the project for production and then preview the built application locally. This is useful for testing before deployment.
```bash
npm run build
npm run preview
```
--------------------------------
### Vento Template Syntax Examples
Source: https://github.com/riipandi/vitto/blob/main/docs/04-templating.md
Demonstrates basic Vento template syntax including variables, expressions, filters (pipes), and comments. These are fundamental building blocks for creating dynamic templates.
```vento
{{ variableName }}
```
```vento
{{ 1 + 2 }}
{{ user.name }}
{{ items.length }}
```
```vento
{{ title |> uppercase }}
{{ content |> safe }}
{{ date |> dateFormat("YYYY-MM-DD") }}
```
```vento
{{# This is a comment #}}
```
--------------------------------
### Example Metadata Configuration
Source: https://github.com/riipandi/vitto/blob/main/docs/12-api-reference.md
Provides an example of how to configure site metadata using the `Metadata` interface. This includes setting basic site information and demonstrating the addition of custom fields for social media and analytics.
```typescript
const metadata: Metadata = {
siteName: 'Tech Blog',
title: 'Tech Blog - Latest Articles',
description: 'A blog about web development and technology',
keywords: ['web development', 'javascript', 'typescript'],
author: 'Jane Smith',
language: 'en',
// Custom fields
social: {
twitter: '@techblog',
github: 'techblog'
},
analytics: {
googleAnalytics: 'UA-XXXXX-Y'
}
}
```
--------------------------------
### Example Dynamic Route Configuration
Source: https://github.com/riipandi/vitto/blob/main/docs/12-api-reference.md
Shows an example of configuring dynamic routes for blog posts. It specifies the 'post' template, uses the 'posts' hook as the data source, and defines functions to extract parameters (slug, id) and generate the file path (e.g., 'blog/my-post-slug.html').
```typescript
{
template: 'post',
dataSource: 'posts',
getParams: (post) => ({
slug: post.slug,
id: post.id
}),
getPath: (post) => `blog/${post.slug}.html`
}
```
--------------------------------
### Complete Blog Page Structure in Vento
Source: https://github.com/riipandi/vitto/blob/main/docs/04-templating.md
Provides a full example of a Vento template for a blog page. It includes layout definition, conditional rendering for posts, looping through posts to include partials, and accessing site metadata.
```vento
{{ layout "layouts/site.vto" }}
{{ metadata.siteName }} Blog
{{ if posts && posts.length > 0 }}
{{ for post of posts }}
{{ include "partials/post-card.vto" {
title: post.title,
excerpt: post.excerpt,
date: post.date,
url: `/blog/${post.slug}.html`
} }}
{{ /for }}
{{ else }}
No posts available yet.
{{ /if }}
```
--------------------------------
### Use npm ci for Faster and Reliable Builds
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Recommends using `npm ci` instead of `npm install` for faster and more reliable dependency installation during builds. `npm ci` ensures that dependencies match the `package-lock.json` exactly.
```bash
# Instead of npm install
npm ci
```
--------------------------------
### Run Vitto Development Servers
Source: https://github.com/riipandi/vitto/blob/main/docs/13-contributing.md
Commands to start development servers for the Vitto project, including the main Vitto package, website, and the create-vitto CLI.
```bash
pnpm dev
pnpm start
pnpm create-vitto
```
--------------------------------
### Configure Environment-Specific Build Settings
Source: https://github.com/riipandi/vitto/blob/main/docs/08-deployment.md
Dynamically configures Vitto build settings based on the current mode (e.g., production). This example enables minification and search index generation only in production.
```typescript
export default defineConfig(({ mode }) => ({
plugins: [
vitto({
minify: mode === 'production',
enableSearchIndex: mode === 'production'
})
]
}))
```
--------------------------------
### Configure Cache Headers for Static Assets
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Provides examples of Nginx-like configuration for setting cache control headers. It demonstrates long caching for hashed assets and short, revalidation-based caching for HTML files.
```nginx
# Long cache for hashed assets
/assets/*
Cache-Control: max-age=31536000, immutable
# Short cache for HTML
/*.html
Cache-Control: max-age=0, must-revalidate, public
```
--------------------------------
### Vento Metadata Access Example
Source: https://github.com/riipandi/vitto/blob/main/docs/04-templating.md
Demonstrates accessing metadata configured in `vite.config.ts` within Vento templates. It shows how to use `metadata.title`, `metadata.description`, and custom fields like `metadata.author`.
```vento
{{ metadata.title }}
{{# Access custom metadata fields #}}
Welcome to {{ metadata.siteName }}
```
```vento
{{ set pageTitle = metadata.title ? `${metadata.title} - ${metadata.siteName}` : metadata.siteName }}
{{ pageTitle }}
```
--------------------------------
### Complete Vitto Configuration Example in TypeScript
Source: https://github.com/riipandi/vitto/blob/main/docs/03-configuration.md
A comprehensive example of a Vitto configuration file using Vite's `defineConfig`. It includes metadata, directory paths, hooks, dynamic routes, and Pagefind options.
```typescript
import { defineConfig } from 'vite'
import vitto, { defineHooks } from 'vitto'
const postsHook = defineHooks('posts', async () => {
const response = await fetch('https://api.example.com/posts')
return response.json()
})
export default defineConfig({
plugins: [
vitto({
metadata: {
siteName: 'My Awesome Blog',
title: 'Welcome to My Blog',
description: 'A blog about web development',
keywords: ['blog', 'web development', 'vitto'],
author: 'Your Name',
language: 'en'
},
pagesDir: 'src/pages',
layoutsDir: 'src/layouts',
partialsDir: 'src/partials',
minify: process.env.NODE_ENV === 'production',
enableSearchIndex: true,
outputStrategy: 'directory',
hooks: {
posts: postsHook
},
dynamicRoutes: [
{
template: 'post',
dataSource: 'posts',
getParams: (post) => ({ id: post.id }),
getPath: (post) => `blog/${post.slug}.html`
}
],
pagefindOptions: {
rootSelector: 'main',
verbose: true
}
})
],
})
```
--------------------------------
### Development and Website Commands
Source: https://github.com/riipandi/vitto/blob/main/docs/13-contributing.md
Commands for running the development server for Vitto and its website, starting the website, and initializing new projects with create-vitto. Also includes commands for building all packages.
```bash
# Development
pnpm dev # Run dev server for vitto and website
pnpm start # Run website only
pnpm create-vitto # Run create-vitto CLI
pnpm build # Build all packages
```
--------------------------------
### Complete Vitto Blog Hooks Example (TypeScript)
Source: https://github.com/riipandi/vitto/blob/main/docs/06-hooks.md
A comprehensive example demonstrating the implementation of two hooks: `postsHook` for fetching all blog posts and `postHook` for fetching a single post by slug. It utilizes Node.js file system modules and the 'gray-matter' library for parsing Markdown frontmatter. This hook definition is intended for a `hooks/blog.ts` file.
```typescript
import { defineHooks } from 'vitto'
import fs from 'node:fs/promises'
import path from 'node:path'
import matter from 'gray-matter'
export const postsHook = defineHooks('posts', async () => {
const postsDir = path.join(process.cwd(), 'content/posts')
const files = await fs.readdir(postsDir)
const posts = await Promise.all(
files
.filter(file => file.endsWith('.md'))
.map(async (file) => {
const content = await fs.readFile(path.join(postsDir, file), 'utf-8')
const { data } = matter(content)
return {
slug: file.replace('.md', ''),
...data
}
})
)
return posts.sort((a, b) =>
new Date(b.date).getTime() - new Date(a.date).getTime()
)
})
export const postHook = defineHooks('post', async (params) => {
if (!params?.slug) return null
const filePath = path.join(process.cwd(), 'content/posts', `${params.slug}.md`)
const content = await fs.readFile(filePath, 'utf-8')
const { data, content: markdown } = matter(content)
return {
slug: params.slug,
...data,
content: markdown
}
})
export default postsHook
```
--------------------------------
### Implement Multi-language Support with Vitto Hooks
Source: https://github.com/riipandi/vitto/blob/main/docs/10-examples.md
This example demonstrates how to create a multi-language site using Vitto's i18n hook. It defines translations for different languages and provides a hook that returns the appropriate translation based on the selected language.
```typescript
import { defineHooks } from 'vitto'
const translations = {
en: {
home: 'Home',
about: 'About',
contact: 'Contact',
readMore: 'Read More',
welcome: 'Welcome to our site'
},
es: {
home: 'Inicio',
about: 'Acerca de',
contact: 'Contacto',
readMore: 'Leer Más',
welcome: 'Bienvenido a nuestro sitio'
},
fr: {
home: 'Accueil',
about: 'À propos',
contact: 'Contact',
readMore: 'Lire la suite',
welcome: 'Bienvenue sur notre site'
}
}
export default defineHooks('i18n', (params) => {
const lang = params?.lang || 'en'
return translations[lang] || translations.en
})
```
--------------------------------
### Configure GitHub Pages Deployment with GitHub Actions
Source: https://github.com/riipandi/vitto/blob/main/docs/08-deployment.md
A GitHub Actions workflow to automatically build and deploy a Vitto site to GitHub Pages on push events to the main branch. It checks out code, sets up Node.js, installs dependencies, builds the site, and deploys the artifacts.
```yaml
name: Deploy to GitHub Pages
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: "pages"
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: "./dist"
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
```
--------------------------------
### Descriptive Parameter Names Example (TypeScript)
Source: https://github.com/riipandi/vitto/blob/main/docs/05-dynamic-routes.md
Demonstrates the importance of using descriptive parameter names in the `getParams` function for better code readability and maintainability.
```typescript
// Good
getParams: (post) => ({ slug: post.slug, id: post.id })
// Avoid
getParams: (post) => ({ p: post.slug })
```
--------------------------------
### Install Vitto using Package Managers
Source: https://github.com/riipandi/vitto/blob/main/packages/vitto-plugin/README.md
This snippet shows how to install Vitto as a development dependency using different package managers: pnpm, npm, and yarn. Ensure you have one of these package managers installed to use these commands.
```sh
# Install with pnpm
pnpm add -D vitto
# Install with npm
npm install --save-dev vitto
# Install with yarn
yarn add --dev vitto
```
--------------------------------
### Markdown Blog Post Example - Vitto
Source: https://github.com/riipandi/vitto/blob/main/docs/10-examples.md
An example of a Markdown file used for a blog post in Vitto. It includes front matter for metadata like title, excerpt, date, author, and tags, followed by the main content. This format is parsed by Vitto hooks to generate dynamic content.
```markdown
---
title: Getting Started with Vitto
excerpt: Learn how to build static sites with Vitto
date: 2024-01-15
author: Your Name
tags:
- vitto
- static-site
- tutorial
---
# Getting Started with Vitto
This is my first blog post built with Vitto...
```
--------------------------------
### Consistent URL Structures Example (JavaScript)
Source: https://github.com/riipandi/vitto/blob/main/docs/05-dynamic-routes.md
Highlights the importance of maintaining a consistent URL structure across different data types for better predictability and user experience.
```javascript
// Good - consistent structure
getPath: (post) => `blog/${post.slug}.html`
getPath: (product) => `products/${product.slug}.html`
// Avoid - inconsistent
getPath: (post) => `${post.slug}.html`
getPath: (product) => `p/${product.id}.html`
```
--------------------------------
### Install Dependencies with PNPM
Source: https://github.com/riipandi/vitto/blob/main/docs/13-contributing.md
Command to install all project dependencies using PNPM, which is the required package manager for this project.
```bash
pnpm install
```
--------------------------------
### Vitto Code Structure and Conventions (TypeScript)
Source: https://github.com/riipandi/vitto/blob/main/docs/13-contributing.md
Demonstrates the recommended naming conventions for files, constants, interfaces, classes, and functions in TypeScript, along with a basic code structure example.
```typescript
// File: my-component.ts
export const DEFAULT_CONFIG = {
// constants
}
export interface MyComponentOptions {
// interface
}
export class MyComponent {
// class
}
export function createComponent() {
// function
}
```
--------------------------------
### Vitto dynamicRoutes Configuration
Source: https://github.com/riipandi/vitto/blob/main/docs/03-configuration.md
Demonstrates how to configure `dynamicRoutes` in Vitto for generating routes programmatically. This example shows setting up routes for blog posts based on a data source.
```typescript
vitto({
metadata: { siteName: 'My Site', title: 'My Site' },
dynamicRoutes: [
{
template: 'post',
dataSource: 'posts',
getParams: (post) => ({ id: post.id }),
getPath: (post) => `blog/${post.slug}.html`
}
]
})
```
--------------------------------
### Example Usage of defineHooks
Source: https://github.com/riipandi/vitto/blob/main/docs/12-api-reference.md
Demonstrates various ways to use the `defineHooks` function, including defining static, asynchronous, and parameterized hooks. These examples showcase how to import `defineHooks` and export different types of hook functions.
```typescript
import { defineHooks } from 'vitto'
// Static hook
export const siteHook = defineHooks('site', () => {
return {
name: 'My Site',
url: 'https://example.com'
}
})
// Async hook
export const postsHook = defineHooks('posts', async () => {
const response = await fetch('https://api.example.com/posts')
return await response.json()
})
// Parameterized hook
export const postHook = defineHooks('post', async (params) => {
if (!params?.id) {
throw new Error('ID is required')
}
const response = await fetch(`https://api.example.com/posts/${params.id}`)
return await response.json()
})
```
--------------------------------
### Configure Netlify Deployment
Source: https://github.com/riipandi/vitto/blob/main/docs/08-deployment.md
Configuration file for deploying a Vitto site to Netlify. It defines the build command, publish directory, and sets up redirects for single-page applications.
```toml
[build]
command = "npm run build"
publish = "dist"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
```
--------------------------------
### TypeScript Code Style Example
Source: https://github.com/riipandi/vitto/blob/main/docs/13-contributing.md
Illustrates recommended TypeScript coding practices, emphasizing the use of interfaces and proper type annotations, while discouraging the use of 'any'.
```typescript
// Good
interface HookData {
title: string
items: string[]
}
function processData(data: HookData): void {
// Implementation
}
// Avoid
function processData(data: any) {
// Implementation
}
```
--------------------------------
### Configure Vercel Deployment
Source: https://github.com/riipandi/vitto/blob/main/docs/08-deployment.md
Configuration file for deploying a Vitto site to Vercel. It specifies the build command, output directory, development command, and the framework used.
```json
{
"buildCommand": "npm run build",
"outputDirectory": "dist",
"devCommand": "npm run dev",
"framework": "vite"
}
```
--------------------------------
### Optimize Image Processing with Sharp in Vitto
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Install and use the 'sharp' library to process and optimize images within your Vitto application. This example demonstrates resizing and converting images to WebP format.
```bash
# Install sharp for image processing
npm install sharp
```
```javascript
// hooks/images.ts
import sharp from 'sharp'
export default defineHooks('optimizedImages', async () => {
const images = await getImages()
await Promise.all(images.map(async (img) => {
await sharp(img.path)
.resize(1200, 800, { fit: 'inside' })
.webp({ quality: 80 })
.toFile(img.outputPath)
}))
return images
})
```
--------------------------------
### Preconnect and DNS-prefetch Origins in Vento
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Demonstrates using `` and `` in a Vento template's `` section. These resource hints help speed up connections to critical third-party origins.
```html
```
--------------------------------
### Blog with Markdown - Vitto Hooks (TypeScript)
Source: https://github.com/riipandi/vitto/blob/main/docs/10-examples.md
Demonstrates how to create hooks in Vitto to process Markdown files for a blog. It includes fetching posts, parsing front matter, and rendering Markdown content. Dependencies include 'vitto', 'node:fs/promises', 'node:path', 'gray-matter', and 'marked'.
```typescript
import { defineHooks } from 'vitto'
import fs from 'node:fs/promises'
import path from 'node:path'
import matter from 'gray-matter'
import { marked } from 'marked'
export const postsHook = defineHooks('posts', async () => {
const postsDir = path.join(process.cwd(), 'content/posts')
const files = await fs.readdir(postsDir)
const posts = await Promise.all(
files
.filter(file => file.endsWith('.md'))
.map(async (file) => {
const filePath = path.join(postsDir, file)
const content = await fs.readFile(filePath, 'utf-8')
const { data, content: markdown } = matter(content)
return {
slug: file.replace('.md', ''),
title: data.title,
excerpt: data.excerpt,
date: data.date,
author: data.author,
tags: data.tags || [],
content: await marked(markdown)
}
})
)
return posts.sort((a, b) =>
new Date(b.date).getTime() - new Date(a.date).getTime()
)
})
export const postHook = defineHooks('post', async (params) => {
if (!params?.slug) return null
const filePath = path.join(process.cwd(), 'content/posts', `${params.slug}.md`)
try {
const content = await fs.readFile(filePath, 'utf-8')
const { data, content: markdown } = matter(content)
return {
slug: params.slug,
title: data.title,
excerpt: data.excerpt,
date: data.date,
author: data.author,
tags: data.tags || [],
content: await marked(markdown)
}
} catch (error) {
console.error(`Failed to load post: ${params.slug}`, error)
return null
}
})
export default postsHook
```
```typescript
import { defineHooks } from 'vitto'
import { postsHook } from './posts'
export const tagsHook = defineHooks('tags', async () => {
const posts = await postsHook()
const tagMap = new Map()
posts.forEach(post => {
post.tags.forEach(tag => {
if (!tagMap.has(tag)) {
tagMap.set(tag, [])
}
tagMap.get(tag).push(post)
})
})
return Array.from(tagMap.entries()).map(([name, posts]) => ({
name,
slug: name.toLowerCase().replace(/\s+/g, '-'),
count: posts.length,
posts
}))
})
export const tagHook = defineHooks('tag', async (params) => {
if (!params?.slug) return null
const tags = await tagsHook()
return tags.find(t => t.slug === params.slug)
})
export default tagsHook
```
--------------------------------
### Vento Control Flow: Conditionals
Source: https://github.com/riipandi/vitto/blob/main/docs/04-templating.md
Examples of using conditional statements (`if`/`else`) in Vento templates to control rendering based on data. This allows for dynamic content display.
```vento
{{ if user }}
Welcome, {{ user.name }}!
{{ else }}
Please log in.
{{ /if }}
```
```vento
{{ if items.length > 0 }}
{{ for item of items }}
{{ item }}
{{ /for }}
{{ else }}
No items found.
{{ /if }}
```
--------------------------------
### Build and Preview Project for Search Indexing
Source: https://github.com/riipandi/vitto/blob/main/docs/07-search.md
Build your project for production to generate the search index, and then preview the build to test search functionality locally. This process ensures that the search index is created correctly and can be tested before deployment. These commands are typically run using npm.
```bash
# Build for production
npm run build
# Preview the build
npm run preview
```
--------------------------------
### Resource Hints for Preload, Preconnect, and DNS-prefetch in Vento
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Combines various resource hints within a Vento template's ``. It shows how to `preload` critical resources like fonts, `preconnect` to external domains, and `dns-prefetch` for third-party domains.
```html
{{# Preload critical resources #}}
{{# Preconnect to external domains #}}
{{# DNS prefetch for third-party resources #}}
```
--------------------------------
### Vento Nested Layout Example
Source: https://github.com/riipandi/vitto/blob/main/docs/04-templating.md
Illustrates how to create nested layouts in Vento. The `article.vto` layout extends `base.vto` and adds article-specific structure like a header with title and time.
```vento
{{ layout "layouts/base.vto" }}
{{ title }}
{{ content |> safe }}
```
--------------------------------
### Vite Configuration with Vitto Plugin
Source: https://github.com/riipandi/vitto/blob/main/docs/10-examples.md
This Vite configuration file (`vite.config.ts`) sets up the project using Vite and integrates the Vitto plugin. It defines site metadata, custom hooks for data fetching (posts and tags), and dynamic routes for generating pages like individual posts and tag pages. Minification is enabled for production builds.
```typescript
import { defineConfig } from 'vite'
import vitto from 'vitto'
import { postsHook, postHook } from './hooks/posts'
import { tagsHook, tagHook } from './hooks/tags'
export default defineConfig({
plugins: [
vitto({
metadata: {
siteName: 'My Blog',
title: 'My Awesome Blog',
description: 'A blog about web development',
author: 'Your Name',
keywords: ['blog', 'web development', 'vitto']
},
hooks: {
posts: postsHook,
post: postHook,
tags: tagsHook,
tag: tagHook
},
dynamicRoutes: [
{
template: 'post',
dataSource: 'posts',
getParams: (post) => ({ slug: post.slug }),
getPath: (post) => `blog/${post.slug}.html`
},
{
template: 'tag',
dataSource: 'tags',
getParams: (tag) => ({ slug: tag.slug }),
getPath: (tag) => `tags/${tag.slug}.html`
}
],
minify: process.env.NODE_ENV === 'production'
})
]
})
```
--------------------------------
### Build Vitto Site for Production
Source: https://github.com/riipandi/vitto/blob/main/docs/08-deployment.md
This command builds your Vitto static site for production, creating an optimized version in the `dist/` directory. It minifies assets, adds cache-busting hashes, and prepares all static pages for serving.
```bash
npm run build
```
--------------------------------
### Vite Build-Time Environment Variable Configuration (TypeScript)
Source: https://github.com/riipandi/vitto/blob/main/docs/08-deployment.md
Configures Vite to expose environment variables at build time. This example shows how to define `import.meta.env.VITE_API_URL` using `process.env.VITE_API_URL` within `vite.config.ts`.
```typescript
// vite.config.ts
export default defineConfig({
define: {
'import.meta.env.VITE_API_URL': JSON.stringify(process.env.VITE_API_URL)
}
})
```
--------------------------------
### Initialize Vitto Plugin with Options
Source: https://github.com/riipandi/vitto/blob/main/docs/12-api-reference.md
Demonstrates how to import and use the main Vitto plugin function with basic options, including site metadata. This is the primary way to integrate Vitto into a Vite project.
```typescript
import vitto from 'vitto'
export default defineConfig({
plugins: [
vitto({
metadata: {
siteName: 'My Site',
title: 'My Site'
}
// other options
})
]
})
```
--------------------------------
### Conditionally Load Scripts in Vitto Templates
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Control script loading based on environment variables. This example shows how to load an analytics script only in production environments to avoid unnecessary loading during development.
```vento
{{# Load analytics only in production #}}
{{ if !isDev }}
{{ /if }}
```
--------------------------------
### Vento Built-in Filters Examples
Source: https://github.com/riipandi/vitto/blob/main/docs/04-templating.md
Demonstrates the usage of common built-in Vento filters, including `safe` for rendering HTML, and others like `uppercase`, `lowercase`, `trim`, `join`, and `fixed` for data manipulation.
```vento
{{ htmlContent |> safe }}
```
```vento
{{ text |> uppercase }}
{{ text |> lowercase }}
{{ text |> trim }}
{{ array |> join(", ") }}
{{ number |> fixed(2) }}
```
--------------------------------
### Vento Template Syntax Examples
Source: https://context7.com/riipandi/vitto/llms.txt
These snippets demonstrate the Vento template syntax for creating HTML pages. They showcase layout inheritance, variable usage, conditional statements, loops, and partial includes, along with comments explaining their purpose.
```vento
{{# src/layouts/base.vto - Base layout template #}}
{{ set pageTitle = metadata.title ? `${metadata.title} - ${metadata.siteName}` : metadata.siteName }}
{{ pageTitle |> safe }}
{{ renderAssets() |> safe }}
{{ include "partials/header.vto" }}
{{ content |> safe }}
{{ include "partials/footer.vto" }}
```
```vento
{{# src/pages/blog.vto - Blog listing page #}}
{{ layout "layouts/base.vto" }}
{{ metadata.siteName }} Blog
{{ if posts && posts.length > 0 }}
{{ for post, index of posts }}
{{ include "partials/post-card.vto" {
title: post.title,
excerpt: post.excerpt,
date: post.date,
url: `/blog/${post.slug}.html`
} }}
{{ /for }}
Read more
```
--------------------------------
### Vitto Configuration for Multiple Dynamic Routes (TypeScript)
Source: https://github.com/riipandi/vitto/blob/main/docs/05-dynamic-routes.md
Demonstrates how to configure the Vitto plugin in Vite to handle multiple dynamic routes. This example shows configurations for blog posts, products, and documentation pages, each using a different template and data source, and defining custom `getParams` and `getPath` functions for each.
```typescript
import { defineConfig } from 'vite'
import vitto from 'vitto'
export default defineConfig({
plugins: [
vitto({
metadata: {
siteName: 'My Site',
title: 'My Site'
},
dynamicRoutes: [
// Blog posts
{
template: 'post',
dataSource: 'posts',
getParams: (post) => ({ slug: post.slug }),
getPath: (post) => `blog/${post.slug}.html`
},
// Products
{
template: 'product',
dataSource: 'products',
getParams: (product) => ({ id: product.id }),
getPath: (product) => `products/${product.slug}.html`
},
// Documentation pages
{
template: 'doc',
dataSource: 'docs',
getParams: (doc) => ({ path: doc.path }),
getPath: (doc) => `docs/${doc.path}.html`
}
]
})
]
})
```
--------------------------------
### Parallel Processing of Data in Vitto Hooks
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Illustrates how to process data in parallel within Vitto hooks using `Promise.all`. This example fetches markdown files and processes them concurrently to improve build performance.
```typescript
// Process data in parallel
export default defineHooks('posts', async () => {
const files = await getMarkdownFiles()
// Process in parallel
const posts = await Promise.all(
files.map(async (file) => {
return await processMarkdown(file)
})
)
return posts
})
```
--------------------------------
### Vitto Vite Configuration and Library Integration
Source: https://github.com/riipandi/vitto/blob/main/docs/14-comparison.md
Demonstrates Vitto's streamlined approach to configuration and library integration using Vite. It shows how Vite handles CSS processing, HMR, and transpilation automatically, and how to import libraries like htmx and Alpine.js.
```typescript
// vite.config.ts - Vite handles everything
import { defineConfig } from 'vite'
import vitto from 'vitto'
export default defineConfig({
plugins: [vitto({
metadata: { siteName: 'My Site', title: 'My Site' }
})],
// CSS processing is automatic
// HMR is built-in
// Modern JS is transpiled automatically
})
```
```typescript
// src/main.ts - Import libraries like any Vite app
import 'htmx.org'
import Alpine from 'alpinejs'
import './style.css' // Processed automatically
window.Alpine = Alpine
Alpine.start()
```
--------------------------------
### Configure Vitto for Dynamic Product Routes
Source: https://github.com/riipandi/vitto/blob/main/docs/10-examples.md
This configuration sets up Vitto to generate dynamic routes for products. It defines metadata, hooks for fetching product data, and dynamic route configurations including data sources, parameter extraction, and path generation.
```typescript
import {
defineConfig
} from 'vite'
import vitto from 'vitto'
import { productsHook, productHook, categoriesHook } from './hooks/products'
export default defineConfig({
plugins: [
vitto({
metadata: {
siteName: 'My Shop',
title: 'My Shop - Quality Products',
description: 'Shop quality products at great prices',
keywords: ['shop', 'ecommerce', 'products']
},
hooks: {
products: productsHook,
product: productHook,
categories: categoriesHook
},
dynamicRoutes: [
{
template: 'product',
dataSource: 'products',
getParams: (product) => ({ id: product.id }),
getPath: (product) => `products/${product.slug}.html`
}
]
})
]
})
```
--------------------------------
### Configure Dynamic Routes with Data Source in Vitto
Source: https://github.com/riipandi/vitto/blob/main/docs/06-hooks.md
An example of configuring dynamic routes in `vite.config.ts` for a 'post' template. It specifies 'posts' as the data source, defines how to get parameters from the data, and how to generate the URL path.
```typescript
// vite.config.ts
vitto({
metadata: {
siteName: 'My Blog',
title: 'My Blog'
},
dynamicRoutes: [
{
template: 'post',
dataSource: 'posts',
getParams: (post) => ({ slug: post.slug }),
getPath: (post) => `blog/${post.slug}.html`
}
]
})
```
--------------------------------
### Service Worker for Caching Assets
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Implements a basic service worker script (`public/sw.js`) to cache essential application assets. It handles the 'install' event to pre-cache files and the 'fetch' event to serve cached responses when available.
```javascript
// public/sw.js
const CACHE_NAME = 'vitto-v1'
const urlsToCache = [
'/',
'/styles.css',
'/main.js'
]
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(urlsToCache))
)
})
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => response || fetch(event.request))
)
})
```
--------------------------------
### Subset Fonts using glyphhanger
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Shows how to subset font files to include only necessary characters, reducing file size. This example uses the `glyphhanger` tool via npx to generate WOFF2 formatted subsets and CSS.
```bash
npx glyphhanger --subset=font.ttf --formats=woff2 --css
```
--------------------------------
### Optimize Data Fetching and Transformation in Vitto Hooks
Source: https://github.com/riipandi/vitto/blob/main/docs/09-performance.md
Efficiently fetch and transform data within Vitto hooks. This example demonstrates selecting only necessary fields from posts to reduce the payload size when displaying a list of posts.
```javascript
export default defineHooks('posts', async () => {
const posts = await getAllPosts()
// Only return fields needed for display
return posts.map(post => ({
slug: post.slug,
title: post.title,
excerpt: post.excerpt,
date: post.date
// Don't include full content in list view
}))
})
```
--------------------------------
### Vitto CLI Commands: Development, Build, and Preview
Source: https://github.com/riipandi/vitto/blob/main/docs/12-api-reference.md
Provides essential command-line interface commands for interacting with the Vitto project. Includes commands for starting a development server, building the production site, and previewing the build locally.
```bash
npm run dev
```
```bash
npm run build
```
```bash
npm run preview
```
--------------------------------
### Vento Partial for Post Card
Source: https://github.com/riipandi/vitto/blob/main/docs/04-templating.md
An example of a Vento partial template (`post-card.vto`) designed to display individual blog post summaries. It takes parameters like title, excerpt, date, and URL to render a consistent card layout.
```vento
Read more →
```
--------------------------------
### List Available Vitto Project Templates
Source: https://github.com/riipandi/vitto/blob/main/packages/create-vitto/README.md
View a list of all available templates for scaffolding a Vitto project. This command helps users discover different project configurations.
```bash
# npm 7+, extra double-dash is needed:
npm create vitto@latest -- --templates
```
```bash
yarn create vitto@latest --templates
```
```bash
pnpm create vitto@latest --templates
```
```bash
bun create vitto@latest --templates
```
```bash
deno init --npm vitto --templates
```
--------------------------------
### Configure Vite for Vitto with Sitemap Hook
Source: https://github.com/riipandi/vitto/blob/main/docs/10-examples.md
This Vite configuration file sets up the Vitto plugin, including metadata and custom hooks. It specifically registers the 'sitemapHook' to be used for sitemap generation. It requires 'vite' and 'vitto' packages, along with the necessary hook files.
```typescript
import { defineConfig } from 'vite'
import vitto from 'vitto'
import sitemapHook from './hooks/sitemap'
import { postsHook, postHook } from './hooks/posts'
export default defineConfig({
plugins: [
vitto({
metadata: {
siteName: 'My Site',
title: 'My Site',
description: 'A website built with Vitto'
},
hooks: {
posts: postsHook,
post: postHook,
sitemap: sitemapHook
}
})
]
})
```
--------------------------------
### Integrate Tailwind CSS with Vitto (Vite Plugin)
Source: https://github.com/riipandi/vitto/blob/main/docs/14-comparison.md
This snippet demonstrates how to integrate Tailwind CSS into a Vitto project using Vite. It involves installing Tailwind CSS and its Vite plugin, then configuring Vite to use both Vitto and Tailwind CSS plugins. This setup allows for rapid styling with Tailwind CSS within the Vitto framework.
```bash
npm install -D tailwindcss @tailwindcss/vite
```
```typescript
// vite.config.ts
import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'
import vitto from 'vitto'
export default defineConfig({
plugins: [
vitto({
metadata: { siteName: 'My Site', title: 'My Site' }
}),
tailwindcss(),
],
})
```