### Vite Integration Examples
Source: https://github.com/olivere/vite/blob/main/README.md
This section provides links to various examples demonstrating different ways to integrate Vite with the Go backend.
```APIDOC
## Examples
### Simple Helper Function
See the `examples/helper-function-basic` directory for a demonstration of a very basic React app that integrates a Go backend.
### Basic with Handler
See the `examples/basic` directory for a demonstration of a very basic React app that integrates a Go backend.
### Inertia.js
See [this example](https://github.com/danclaytondev/go-inertia-vite) for using Golang with `net/http`, [Inertia.js](https://inertiajs.com/) and this library for managing Vite assets.
### Multi Page App
For Vite apps that have multiple entry points, you can pass the entry point by creating a separate `vite.Handler` and specifying the `ViteEntry` field. See the `examples/multi-page-app` directory for an example.
### Template Registration
You can use custom HTML templates in your Go backend for serving different React pages. See the `examples/template-registry` directory for an example.
### Router App
This application consists of a Go backend, serving a Vite-based app using TanStack Router and TanStack Query libraries. See the the `examples/router` directory.
```
--------------------------------
### Run Go Backend in Production Mode (Shell)
Source: https://github.com/olivere/vite/blob/main/examples/multi-page-app/README.md
Launches the Go backend server in production mode. It embeds the assets from the 'dist' directory, serving the pre-built Vite application.
```shell
$ go run main.go
```
--------------------------------
### Run Go Backend in Development Mode (Shell)
Source: https://github.com/olivere/vite/blob/main/examples/multi-page-app/README.md
Launches the Go backend server in development mode, incorporating the Vite development server. This allows for seamless integration with HMR.
```shell
$ go run main.go -dev
```
--------------------------------
### Configure Vite for Multi-Page App (TypeScript)
Source: https://github.com/olivere/vite/blob/main/examples/multi-page-app/README.md
Configures Vite to support multiple entry points for a multi-page application. It enables manifest generation for asset tracking and specifies 'main' and 'nested' as the entry points, referencing their respective TypeScript files.
```typescript
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
build: {
// generates .vite/manifest.json in outDir
manifest: true,
rollupOptions: {
// overwrite default .html entry and include a secondary
input: {
main: "/src/main.tsx",
nested: "/src/nested.tsx",
},
},
},
})
```
--------------------------------
### Serve Admin App Assets with Custom Prefix (Go)
Source: https://github.com/olivere/vite/blob/main/examples/multiple-vite-apps/README.md
Configures an HTTP handler to serve static assets for the admin application with a custom URL prefix. This is necessary in production when a custom AssetsURLPrefix is used with Vite.
```go
assetsAdminApp, _ := fs.Sub(app.DistFS, "admin-app")
assetsAdminAppFS := http.FileServer(http.FS(assetsAdminApp))
mux.Handle("/admin-app/assets/", http.StripPrefix("/admin-app", assetsAdminAppFS))
```
--------------------------------
### Run Vite Dev Server
Source: https://github.com/olivere/vite/blob/main/examples/helper-function-basic/README.md
Command to start the Vite development server. This enables hot module replacement (HMR) for rapid frontend development.
```shell
npm run dev
```
--------------------------------
### Generate Main Vite App Tags (Go)
Source: https://github.com/olivere/vite/blob/main/examples/multiple-vite-apps/README.md
Generates HTML tags for embedding assets of the main Vite application (Vue.js). It configures Vite with development server URL, entry point, and filesystem. Handles potential errors during fragment generation.
```go
func ViteAppTags() template.HTML {
var err error
assetsApp, _ := fs.Sub(app.DistFS, "app")
viteConfig := vite.Config{
IsDev: app.InDevelopment,
ViteURL: "http://localhost:5173", // Development URL for 'app'
ViteEntry: "src/main.tsx",
ViteTemplate: vite.ReactTs,
FS: assetsApp,
}
viteFragment, err := vite.HTMLFragment(viteConfig)
if err != nil {
log.Printf("Vite fragment error: %v", err)
return ""
}
return viteFragment.Tags
}
```
--------------------------------
### Custom HTML Template for Go Server
Source: https://github.com/olivere/vite/blob/main/examples/template-registry/README.md
An example of a custom HTML template string used in Go. It includes placeholders for metadata, development preamble, stylesheets, modules, and scripts, making it dynamic.
```go
var (
customIndex = `
{{- if .Metadata }}
{{ .Metadata }}
{{- end }}
{{- if .IsDev }}
{{ .PluginReactPreamble }}
{{- else }}
{{- if .StyleSheets }}
{{ .StyleSheets }}
{{- end }}
{{- if .Modules }}
{{ .Modules }}
{{- end }}
{{- if .PreloadModules }}
{{ .PreloadModules }}
{{- end }}
{{- end }}
{{- if .Scripts }}
{{ .Scripts }}
{{- end }}
My Custom Header
`
)
```
--------------------------------
### Generate Admin Vite App Tags with Prefix (Go)
Source: https://github.com/olivere/vite/blob/main/examples/multiple-vite-apps/README.md
Generates HTML tags for embedding assets of the admin Vite application (ReactTS). It configures Vite with a custom assets URL prefix for production, development server URL, entry point, and filesystem. Handles potential errors.
```go
func ViteAdminTags() template.HTML {
var err error
assetsApp, _ := fs.Sub(app.DistFS, "admin-app")
viteConfig := vite.Config{
IsDev: app.InDevelopment,
ViteURL: "http://localhost:5174/admin", // Development URL for 'admin'
ViteEntry: "src/main.js",
ViteTemplate: vite.Vue,
FS: assetsApp,
AssetsURLPrefix: "/admin-app", // Custom prefix
}
viteFragment, err := vite.HTMLFragment(viteConfig)
if err != nil {
log.Printf("Vite fragment error: %v", err)
return ""
}
return viteFragment.Tags
}
```
--------------------------------
### Bash: Run Vite Dev Server
Source: https://github.com/olivere/vite/blob/main/docs/guide/usage.md
Command to start the Vite development server. This is typically run in a separate terminal within the frontend project directory. It enables hot module replacement and other development features.
```bash
cd frontend
npm run dev
```
--------------------------------
### Integrate ESLint React Plugin Configuration (TypeScript)
Source: https://github.com/olivere/vite/blob/main/examples/multiple-vite-apps/frontend/app/README.md
This configuration integrates the `eslint-plugin-react` into your ESLint setup for a TypeScript project. It involves setting the React version and enabling recommended rules from the plugin. Ensure `eslint-plugin-react` is installed as a dependency.
```javascript
// eslint.config.js
import react from 'eslint-plugin-react'
export default tseslint.config({
// Set the react version
settings: { react: { version: '18.3' } },
plugins: {
// Add the react plugin
react,
},
rules: {
// other rules...
// Enable its recommended rules
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
},
})
```
--------------------------------
### Configure ESLint with Type-Aware Rules (TypeScript)
Source: https://github.com/olivere/vite/blob/main/examples/multiple-vite-apps/frontend/app/README.md
This snippet shows how to configure ESLint to enable type-aware linting rules in a TypeScript project. It requires specifying TypeScript project files and the root directory for parsing. This setup enhances code quality by leveraging TypeScript's type checking during linting.
```javascript
export default tseslint.config({
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
},
})
```
--------------------------------
### Vite Configuration Parameters
Source: https://github.com/olivere/vite/blob/main/README.md
This section details the available configuration parameters for `vite.Config`, outlining their types, descriptions, and default values.
```APIDOC
## Configuration
This section lists all configuration parameters of the `vite.Config`.
### Parameters
- **IsDev** (bool) - Instruct whether to link to dev Vite server or built assets in 'prod'. Useful Default: `false`
- **FS** (fs.FS) - FS containing the Vite assets (and manifest).
- **ViteEntry** (string) - Optional. Entrypoint for the Vite application. Usually a main Javascript file. This is the top of the dependency tree and Vite will import dependencies based on this entrypoint. Useful Default: `src/main.tsx`
- **ViteURL** (string) - Optional. Local URL for the Vite development server. Not used in production mode. Useful Default: `http://localhost:5173`
- **ViteManifest** (string) - Optional. File path of the manifest file (relative to FS). Only used in production mode. Useful Default: `.vite/manifest.json`
- **ViteTemplate** (Scaffolding) - Optional. A enum-like type that instructs this library what preambles to inject based on what project type (React, Vue etc). Needed for React applications to enable HMR etc. Useful Default: React (includes React preamble)
- **PublicFS** (fs.FS) - Optional. Only used with the `vite.NewHandler` to serve the public directory for you. Not used when this library is used as a helper template function.
### Request Example
```json
{
"IsDev": true,
"FS": null,
"ViteEntry": "src/main.js",
"ViteURL": "http://localhost:3000",
"ViteManifest": ".vite/manifest.json",
"ViteTemplate": "React",
"PublicFS": null
}
```
### Response
#### Success Response (200)
- **Configuration Status** (string) - Indicates the success or failure of applying the configuration.
#### Response Example
```json
{
"Configuration Status": "Applied successfully"
}
```
```
--------------------------------
### Configure Vite Handler for Development and Production in Go
Source: https://context7.com/olivere/vite/llms.txt
Demonstrates various configurations for the Vite handler, supporting development servers with hot reloading, production builds with custom asset prefixes for CDNs, and serving multiple Vite applications from different base paths. It includes options for specifying framework templates and embedded file systems.
```go
package main
import (
"embed"
"io/fs"
"log"
"net/http"
"os"
"github.com/olivere/vite"
)
//go:embed all:frontend/dist
var frontendDist embed.FS
func main() {
// Example 1: Development with Vue
devHandler, _ := vite.NewHandler(vite.Config{
FS: os.DirFS("./frontend"),
IsDev: true,
ViteURL: "http://localhost:5173",
ViteEntry: "src/main.js",
ViteTemplate: vite.Vue,
PublicFS: os.DirFS("./frontend/public"),
})
// Example 2: Production with custom asset prefix for CDN
prodFS, _ := fs.Sub(frontendDist, "frontend/dist")
prodHandler, _ := vite.NewHandler(vite.Config{
FS: prodFS,
IsDev: false,
ViteManifest: ".vite/manifest.json",
AssetsURLPrefix: "/assets",
ViteTemplate: vite.ReactSwcTs,
})
// Example 3: Multiple Vite apps with different base paths
adminFS, _ := fs.Sub(frontendDist, "frontend/admin/dist")
adminHandler, _ := vite.NewHandler(vite.Config{
FS: adminFS,
IsDev: false,
ViteEntry: "src/admin.tsx",
AssetsURLPrefix: "/admin/assets",
})
// Example 4: Svelte application
svelteHandler, _ := vite.NewHandler(vite.Config{
FS: os.DirFS("./svelte-app"),
IsDev: true,
ViteURL: "http://localhost:5174",
ViteEntry: "src/main.js",
ViteTemplate: vite.Svelte,
})
// Route the handlers
mux := http.NewServeMux()
mux.Handle("/", prodHandler)
mux.Handle("/admin/", http.StripPrefix("/admin", adminHandler))
log.Fatal(http.ListenAndServe(":8080", mux))
}
```
--------------------------------
### Serve Static Assets with net/http in Go
Source: https://github.com/olivere/vite/blob/main/README.md
Provides functions to serve static assets for Vite applications using Go's net/http package. It distinguishes between development and production modes, serving assets from the appropriate directories. Includes a helper function to configure the ServeMux.
```go
if *isDev {
serverStaticFolder(mux, "/src/assets/", os.DirFS("frontend/src/assets"))
} else {
serverStaticFolder(mux, "/assets/", os.DirFS("frontend/dist/assets"))
}
func serverStaticFolder(mux *http.ServeMux, path string, fs fs.FS) {
mux.Handle(path, http.StripPrefix(path, http.FileServerFS(fs)))
}
```
--------------------------------
### Initialize Vite Handler in Development Mode (Go)
Source: https://github.com/olivere/vite/blob/main/README.md
Initializes the Vite HTTP handler for development. It requires a file system pointing to the Vite source code and sets the handler to development mode. Dependencies include the 'vite' Go package and standard Go libraries like 'os' and 'fmt'. It optionally takes Vite server URL and entry point configurations.
```go
// Serve in development mode (assuming your frontend code is in ./frontend,
// relative to your binary)
v, err := vite.NewHandler(vite.Config{
FS: os.DirFS("./frontend"),
IsDev: true,
PublicFS: os.DirFS("./frontend/public"), // optional: we use the "public" directory under "FS" by default
ViteURL: "http://localhost:5173", // optional: we use "http://localhost:5173" by default
ViteEntry: "src/main.js" // optional: depending on your frontend stack
})
if err != nil { ... }
```
--------------------------------
### Create Vite React TS App
Source: https://github.com/olivere/vite/blob/main/examples/helper-function-basic/README.md
Command to create a new Vite project with React and TypeScript template. This initializes the project structure and necessary dependencies.
```shell
npm create vite@latest example -- --template react-ts
```
--------------------------------
### Build and Run Go Server in Production Mode
Source: https://github.com/olivere/vite/blob/main/examples/template-registry/README.md
Commands to build the Vite frontend for production and then run the Go application. The Go application will embed the built assets, serving them directly.
```sh
npm run build
go run main.go
```
--------------------------------
### Create Vite HTTP Handler (Go)
Source: https://context7.com/olivere/vite/llms.txt
Creates an HTTP handler for serving Vite assets and managing routing. It supports both development mode (proxying to Vite dev server) and production mode (serving pre-built assets from an embedded filesystem). Requires Vite configuration including the filesystem, development mode flag, Vite server URL, entry point, template type, and public filesystem.
```go
package main
import (
"embed"
"flag"
"io/fs"
"log"
"net/http"
"os"
"github.com/olivere/vite"
)
//go:embed all:dist
var distFS embed.FS
func main() {
isDev := flag.Bool("dev", false, "run in development mode")
flag.Parse()
var handler *vite.Handler
var err error
if *isDev {
// Development: serve from local filesystem, proxy to Vite dev server
handler, err = vite.NewHandler(vite.Config{
FS: os.DirFS("./frontend"),
IsDev: true,
ViteURL: "http://localhost:5173",
ViteEntry: "src/main.tsx",
ViteTemplate: vite.React,
PublicFS: os.DirFS("./frontend/public"),
})
} else {
// Production: serve from embedded dist directory
distSubFS, _ := fs.Sub(distFS, "dist")
handler, err = vite.NewHandler(vite.Config{
FS: distSubFS,
IsDev: false,
ViteManifest: ".vite/manifest.json",
})
}
if err != nil {
log.Fatal(err)
}
http.Handle("/", handler)
log.Println("Server started on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
--------------------------------
### Configure Vite for Manifest and Entry Point
Source: https://github.com/olivere/vite/blob/main/examples/helper-function-basic/README.md
TypeScript configuration for Vite. It enables manifest file generation and overwrites the default HTML entry point to '/src/main.tsx'.
```typescript
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
build: {
// generates .vite/manifest.json in outDir
manifest: true,
rollupOptions: {
// overwrite default .html entry
input: "/src/main.tsx",
},
},
})
```
--------------------------------
### Build Vite for Production
Source: https://github.com/olivere/vite/blob/main/examples/helper-function-basic/README.md
Command to build the Vite project for production. This generates optimized static assets in the 'dist' directory, which are then embedded by the Go binary.
```shell
npm run build
```
--------------------------------
### Bash: Build Vite Application for Production
Source: https://github.com/olivere/vite/blob/main/docs/guide/usage.md
Command to build the Vite application for production deployment. This generates optimized static assets in the `dist` directory, ready to be served by a backend or a static file server.
```bash
cd frontend
npm run build
```
--------------------------------
### Initialize Vite Handler in Production Mode (Go)
Source: https://github.com/olivere/vite/blob/main/README.md
Initializes the Vite HTTP handler for production. It embeds the Vite build output (typically the 'dist' directory) into the Go binary using `go:embed` and sets the handler to production mode. The `FS` parameter should be the embedded file system. Dependencies include 'embed' and 'fs' from the Go standard library.
```go
//go:embed all:dist
var distFS embed.FS
func DistFS() fs.FS {
efs, err := fs.Sub(distFS, "dist")
if err != nil {
panic(fmt.Sprintf("unable to serve frontend: %v", err))
}
return efs
}
// Serve in production mode
v, err := vite.NewHandler(vite.Config{
FS: DistFS(),
IsDev: false,
})
if err != nil { ... }
```
--------------------------------
### Add SEO Metadata to Request Context (Go)
Source: https://context7.com/olivere/vite/llms.txt
The `MetadataToContext` function adds comprehensive SEO metadata, including title, description, Open Graph, and Twitter cards, to the request context. This metadata is automatically rendered in the HTML head for server-side rendering. It requires the `github.com/olivere/vite` package and takes a `vite.Metadata` struct as input.
```go
package main
import (
"net/http"
"time"
"github.com/olivere/vite"
)
func articleHandler(viteHandler *vite.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Create comprehensive metadata for an article page
metadata := vite.Metadata{
Title: "Understanding Go and Vite Integration",
Description: "Learn how to integrate Vite with Go backends for modern web applications",
Keywords: []string{"go", "vite", "web development", "backend"},
Authors: []vite.Author{
{Name: "John Doe", URL: "https://example.com/authors/john"},
},
Canonical: "https://example.com/articles/go-vite-integration",
OpenGraph: &vite.OpenGraph{
Title: "Understanding Go and Vite Integration",
Description: "Learn how to integrate Vite with Go backends",
URL: "https://example.com/articles/go-vite-integration",
Type: "article",
SiteName: "Tech Blog",
PublishedTime: time.Now(),
Images: []vite.OpenGraphImage{
{
URL: "https://example.com/images/article-cover.jpg",
Width: 1200,
Height: 630,
Alt: "Go and Vite logos",
},
},
},
Twitter: &vite.Twitter{
Card: "summary_large_image",
Title: "Understanding Go and Vite Integration",
Description: "Learn how to integrate Vite with Go backends",
Creator: "@johndoe",
Images: []string{"https://example.com/images/article-cover.jpg"},
},
Viewport: &vite.Viewport{
Width: "device-width",
InitialScale: 1.0,
ThemeColor: []vite.ThemeColor{
{Color: "#3b82f6", Media: "(prefers-color-scheme: light)"},
{Color: "#1e40af", Media: "(prefers-color-scheme: dark)"},
},
},
}
ctx = vite.MetadataToContext(ctx, metadata)
viteHandler.ServeHTTP(w, r.WithContext(ctx))
}
}
```
--------------------------------
### Configuration Options
Source: https://github.com/olivere/vite/blob/main/docs/guide/usage.md
Provides a comprehensive list of configuration parameters for `vite.Config`, detailing their types, descriptions, requirements, and default values.
```APIDOC
## Configuration Options
A complete list of all configuration parameters for the `vite.Config`.
### Parameters
#### `FS`
* **Type**: `fs.FS`
* **Description**: Filesystem containing the Vite assets and manifest. In production, this is the Vite output directory (usually "dist"). In development, this is typically the root directory of the Vite app.
* **Required**: Yes
* **Default Value**: None
#### `PublicFS`
* **Type**: `fs.FS`
* **Description**: Filesystem to serve public files from (usually the "public" directory). Only used in development mode.
* **Required**: No
* **Default Value**: None
#### `IsDev`
* **Type**: `bool`
* **Description**: Determines whether to link to dev Vite server or built assets in 'prod' mode.
* **Required**: Yes
* **Default Value**: `false`
#### `ViteEntry`
* **Type**: `string`
* **Description**: Entrypoint for the Vite application. Useful for implementing secondary routes as described in the Multi-Page App section of the Vite guide.
* **Required**: No
* **Default Value**: `src/main.tsx`
#### `ViteURL`
* **Type**: `string`
* **Description**: Local URL for the Vite development server. Only used in development mode.
* **Required**: No
* **Default Value**: `http://localhost:5173`
#### `ViteManifest`
* **Type**: `string`
* **Description**: File path of the manifest file (relative to FS). Only used in production mode.
* **Required**: No
* **Default Value**: `.vite/manifest.json`
#### `ViteTemplate`
* **Type**: `Scaffolding` (Enum)
* **Description**: Enum type that specifies which frontend framework is being used. This determines if framework-specific code (preamble) needs to be injected.
* **Required**: No
* **Default Value**: None
#### `AssetsURLPrefix`
* **Type**: `string`
* **Description**: URL prefix for serving asset files. Only used in production mode to construct paths for assets based on the Vite manifest. Useful when serving multiple builds from different base paths.
* **Required**: No
* **Default Value**: `""` (empty string)
### ViteTemplate and Preamble
::: info FRAMEWORK INTEGRATION
The `ViteTemplate` option is needed when:
1. You are running in development mode (`IsDev` is `true`)
2. You are using a frontend framework that requires special setup for Hot Module Replacement (HMR)
:::
A **preamble** is a special code snippet injected into the HTML that enables framework-specific features during development. For example, React requires a specific preamble to enable Fast Refresh (Hot Module Replacement). The preamble is a JavaScript snippet that:
- Imports the React Refresh Runtime from the Vite development server
- Injects it into the global window hook
- Sets up necessary refresh registration functions
Without this preamble, React components would not update in real-time during development when you make changes to your code. The library automatically adds the correct preamble based on your `ViteTemplate` setting.
### Scaffolding Options
The `ViteTemplate` field accepts a `Scaffolding` enum with the following values:
| Value | Description | Requires Preamble |
|------------|------------------------------------|-------------------|
| React | Template for a React project | ✅ |
| ReactTs | Template for a TypeScript React project | ✅ |
| ReactSwc | Template for a React project using SWC compiler | ✅ |
| ReactSwcTs | Template for a TypeScript React project using SWC | ✅ |
| Vue | Template for a Vue.js project | ❌ |
| VueTs | Template for a TypeScript Vue.js project | ❌ |
| Vanilla | Template for a Vanilla JavaScript project | ❌ |
| VanillaTs | Template for a Vanilla TypeScript project | ❌ |
| Preact | Template for a Preact project | ❌ |
| PreactTs | Template for a TypeScript Preact project | ❌ |
| Lit | Template for a Lit project | ❌ |
| LitTs | Template for a TypeScript Lit project | ❌ |
| Svelte | Template for a Svelte project | ❌ |
| SvelteTs | Template for a TypeScript Svelte project | ❌ |
| Solid | Template for a Solid project | ❌ |
| SolidTs | Template for a TypeScript Solid project | ❌ |
| Qwik | Template for a Qwik project | ❌ |
| QwikTs | Template for a TypeScript Qwik project | ❌ |
| None | Opt out of using a specific scaffolding | ❌ |
### Additional Notes
::: tip
- React-based templates (React, ReactTs, ReactSwc, ReactSwcTs) require a preamble for Hot Module Replacement (HMR) to work properly in development mode.
- The `PublicFS` field is optional. If not provided, the system will check if the "public" directory exists in the Vite app and serve files from there.
:::
::: warning
- In development mode, the `ViteURL` parameter defines the base URL for assets, making the `AssetsURLPrefix` parameter unnecessary.
- The manifest file is used in production mode to map original file paths to transformed file paths.
:::
```
--------------------------------
### Go: Create Vite HTTP Handler for Production Mode with Embedded Assets
Source: https://github.com/olivere/vite/blob/main/docs/guide/usage.md
Sets up a Vite HTTP handler for production mode using embedded assets. It embeds the Vite build output (`dist` directory) into the Go binary for self-contained serving. Requires the `embed` package and a function to create a file system from the embedded assets.
```go
//go:embed all:dist
var distFS embed.FS
func DistFS() fs.FS {
efs, err := fs.Sub(distFS, "dist")
if err != nil {
panic(fmt.Sprintf("unable to serve frontend: %v", err))
}
return efs
}
// Create a handler in production mode
handler, err := vite.NewHandler(vite.Config{
FS: DistFS(), // Embedded dist directory
IsDev: false, // Disable development mode
})
if err != nil {
panic(err)
}
// Use the handler
http.Handle("/", handler)
```
--------------------------------
### Generate Vite HTML Fragment in Go
Source: https://github.com/olivere/vite/blob/main/README.md
Generates HTML script and link tags to point to Vite assets. It dynamically links to the Vite development server or production build assets based on the provided configuration. Requires Vite build output directory and development mode flag.
```go
viteFragment, err := vite.HTMLFragment(vite.Config{
FS: os.DirFS("frontend/dist"), // required: Vite build output
IsDev: *isDev, // required: true or false
ViteURL: "http://localhost:5173", // optional: defaults to this
ViteEntry: "src/main.js", // optional: dependent on your frontend stack
})
if err != nil {
panic(err)
}
t := template.Must(template.New("name").Parse(indexTemplate))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
pageData := map[string]interface{}{
"Vite": viteFragment,
}
if err = tmpl.Execute(w, pageData); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
indexTemplate := `
My Go Application
{{ .Vite.Tags }}
`
```
--------------------------------
### Run Go Backend in Production Mode
Source: https://github.com/olivere/vite/blob/main/examples/helper-function-basic/README.md
Command to run the Go backend application in production mode. It serves the static assets generated by 'npm run build'.
```shell
go run main.go
```
--------------------------------
### Go: Generate Vite HTML Fragments with Helper Function
Source: https://github.com/olivere/vite/blob/main/docs/guide/usage.md
Initializes a Vite helper function to generate HTML tags for connecting Go applications to Vite assets. It supports both development and production modes, linking to the Vite dev server or built assets respectively. Requires Vite build output directory and a flag for development/production mode. Optionally accepts Vite URL and entry point.
```go
viteFragment, err := vite.HTMLFragment(vite.Config{
FS: os.DirFS("frontend/dist"), // Required: Vite build output directory
IsDev: *isDev, // Required: Development or Production mode
ViteURL: "http://localhost:5173", // Optional: Defaults to this URL
ViteEntry: "src/main.js", // Optional: Depends on your frontend setup
})
if err != nil {
panic(err)
}
// Create a template
tmpl := template.Must(template.New("index").Parse(indexTemplate))
// Serve the template
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
pageData := map[string]interface{}{
"Vite": viteFragment,
}
if err = tmpl.Execute(w, pageData);
err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
// Template with Vite tags
indexTemplate := `
My Go Application
{{ .Vite.Tags }}
`
```
--------------------------------
### Run Go Backend in Development Mode
Source: https://github.com/olivere/vite/blob/main/examples/helper-function-basic/README.md
Command to run the Go backend application with the '-dev' flag. This mode likely serves the Vite development server assets.
```shell
go run main.go -dev
```
--------------------------------
### Go: Create Vite HTTP Handler for Development Mode
Source: https://github.com/olivere/vite/blob/main/docs/guide/usage.md
Creates a Vite HTTP handler for development mode in a Go server. This handler manages serving frontend assets directly from the source directory. Requires the frontend source directory, development mode enabled, and optionally allows specifying a public directory, Vite dev server URL, and entry point.
```go
// Create a handler in development mode
handler, err := vite.NewHandler(vite.Config{
FS: os.DirFS("./frontend"), // Source directory of your frontend
IsDev: true, // Enable development mode
PublicFS: os.DirFS("./frontend/public"), // Optional: Serve public directory
ViteURL: "http://localhost:5173", // Optional: Dev server URL
ViteEntry: "src/main.js" // Optional: Entry point
})
if err != nil {
panic(err)
}
// Use the handler
http.Handle("/", handler)
```
--------------------------------
### Go: Serve Vite Assets in Development and Production
Source: https://github.com/olivere/vite/blob/main/docs/guide/usage.md
Configures static asset serving for Vite projects within a Go application. In development, it serves assets from the source directory and the public folder. In production, it serves built assets from the dist directory. Includes a helper function `serveStaticFolder` for managing static file serving.
```go
if isDev {
// Serve assets from the source directory in development
serveStaticFolder(mux, "/src/assets/", os.DirFS("frontend/src/assets"))
// Serve the public folder
serveStaticFolder(mux, "/", os.DirFS("frontend/public"))
}
if !isDev {
// Serve assets from the build directory in production
serveStaticFolder(mux, "/assets/", os.DirFS("frontend/dist/assets"))
// Serve the public folder
serveStaticFolder(mux, "/", os.DirFS("frontend/dist"))
}
// Helper function to serve static files
func serveStaticFolder(mux *http.ServeMux, path string, fs fs.FS) {
mux.Handle(path, http.StripPrefix(path, http.FileServer(http.FS(fs))))
}
```
--------------------------------
### Generate Vite HTML Tags (Go)
Source: https://context7.com/olivere/vite/llms.txt
Generates an HTML fragment containing script and link tags for Vite assets, allowing manual control over HTML templates and routing logic. Requires Vite configuration including the filesystem, development mode flag, Vite server URL, entry point, and template type.
```go
package main
import (
"flag"
"html/template"
"log"
"net/http"
"os"
"github.com/olivere/vite"
)
func main() {
isDev := flag.Bool("dev", false, "development mode")
flag.Parse()
// Generate Vite HTML fragment
viteFragment, err := vite.HTMLFragment(vite.Config{
FS: os.DirFS("frontend/dist"),
IsDev: *isDev,
ViteURL: "http://localhost:5173",
ViteEntry: "src/main.js",
ViteTemplate: vite.ReactSwc,
})
if err != nil {
log.Fatal(err)
}
// Parse HTML template
tmpl := template.Must(template.New("index").Parse(`
My Vite App
{{ .Vite.Tags }}
`))
// Serve the page
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data := map[string]interface{}{
"Vite": viteFragment,
}
if err := tmpl.Execute(w, data);
err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
--------------------------------
### Register Custom Template with Vite Handler (Go)
Source: https://github.com/olivere/vite/blob/main/examples/template-registry/README.md
Go code snippet demonstrating how to instantiate the viteHandler and register a custom HTML template named 'index.html'. This integrates the custom template into the Go server.
```go
viteHandler, err := vite.NewHandler(vite.Config{
FS: os.DirFS("."),
IsDev: true,
ViteURL: "http://localhost:5173",
})
if err != nil {
panic(err)
}
viteHandler.RegisterTemplate("index.html", customIndex)
```
--------------------------------
### Set Default Metadata for Vite Pages in Go
Source: https://context7.com/olivere/vite/llms.txt
Configures global metadata for all pages served by the Vite handler. This includes SEO settings like title, description, OpenGraph tags, robots directives, viewport, and icons. Page-specific metadata can override these defaults.
```go
package main
import (
"log"
"net/http"
"os"
"github.com/olivere/vite"
)
func main() {
handler, err := vite.NewHandler(vite.Config{
FS: os.DirFS("frontend/dist"),
IsDev: false,
})
if err != nil {
log.Fatal(err)
}
// Set default metadata for all pages
defaultMetadata := &vite.Metadata{
Title: "My Application",
Description: "A modern web application built with Go and Vite",
ApplicationName: "MyApp",
Generator: "Vite + Go",
Keywords: []string{"web app", "go", "vite", "spa"},
OpenGraph: &vite.OpenGraph{
SiteName: "My Application",
Type: "website",
Locale: "en_US",
Images: []vite.OpenGraphImage{
{
URL: "https://example.com/og-image.jpg",
Width: 1200,
Height: 630,
},
},
},
Robots: &vite.Robots{
Index: true,
Follow: true,
GoogleBot: &vite.GoogleBot{
Index: true,
Follow: true,
MaxVideoPreview: -1,
MaxImagePreview: "large",
MaxSnippet: -1,
},
},
Viewport: &vite.Viewport{
Width: "device-width",
InitialScale: 1.0,
ColorScheme: "light dark",
},
Icons: &vite.Icons{
Icon: []vite.Icon{
{URL: "/favicon.ico"},
{URL: "/icon.svg", Type: "image/svg+xml"},
},
Apple: []vite.AppleIcon{
{URL: "/apple-touch-icon.png", Sizes: []string{"180x180"}},
},
},
Manifest: "/manifest.json",
}
handler.SetDefaultMetadata(defaultMetadata)
// Individual pages can override default metadata
http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
ctx := vite.MetadataToContext(r.Context(), vite.Metadata{
Title: "About Us",
Description: "Learn more about our team and mission",
})
handler.ServeHTTP(w, r.WithContext(ctx))
})
http.Handle("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
--------------------------------
### Parse Command-Line Flags in Go
Source: https://github.com/olivere/vite/blob/main/README.md
Parses command-line flags for a Go application, specifically for determining the development mode. This allows the application to be run with a flag to enable or disable development-specific features.
```go
var isDev = flag.Bool("dev", false, "run in development mode")
flag.Parse()
```
--------------------------------
### Register Custom HTML Templates for Multi-Page Apps (Go)
Source: https://context7.com/olivere/vite/llms.txt
Registers custom HTML templates for different routes in multi-page applications using the vite Go package. It allows each template to have a unique structure while sharing Vite assets. This is useful for creating distinct layouts for different sections of an application, such as a homepage and an admin panel.
```go
package main
import (
"embed"
"io/fs"
"log"
"net/http"
"github.com/olivere/vite"
)
//go:embed all:dist
var distFS embed.FS
func main() {
distSubFS, _ := fs.Sub(distFS, "dist")
handler, err := vite.NewHandler(vite.Config{
FS: distSubFS,
IsDev: false,
ViteEntry: "src/main.tsx",
})
if err != nil {
log.Fatal(err)
}
// Register template for the homepage
handler.RegisterTemplate("index.html", `
Home - My App
{{- if .Metadata }}{{ .Metadata }}{{- end }}
{{- if .IsDev }}
{{ .PluginReactPreamble }}
{{- else }}
{{ .StyleSheets }}{{ .Modules }}{{ .PreloadModules }}
{{- end }}
`)
// Register template for admin panel
handler.RegisterTemplate("admin.html", `
Admin Panel
{{- if .Metadata }}{{ .Metadata }}{{- end }}
{{- if .IsDev }}
{{ .PluginReactPreamble }}
{{- else }}
{{ .StyleSheets }}{{ .Modules }}{{ .PreloadModules }}
{{- end }}
`)
// Route handlers
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
})
http.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
--------------------------------
### Parse Vite Manifest Manually (Go)
Source: https://context7.com/olivere/vite/llms.txt
Parses the Vite manifest.json file to provide custom asset management capabilities. This is useful for scenarios where fine-grained control over asset loading is required or for integration with custom build pipelines. It allows accessing entry points, chunks, and generating HTML tags for assets.
```go
package main
import (
"fmt"
"log"
"os"
"github.com/olivere/vite"
)
func main() {
// Open the Vite manifest file
file, err := os.Open("frontend/dist/.vite/manifest.json")
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Parse the manifest
manifest, err := vite.ParseManifest(file)
if err != nil {
log.Fatal(err)
}
// Get the main entry point
entryPoint := manifest.GetEntryPoint()
if entryPoint != nil {
fmt.Printf("Entry point: %s\n", entryPoint.Src)
fmt.Printf("Output file: %s\n", entryPoint.File)
fmt.Printf("CSS files: %v\n", entryPoint.CSS)
fmt.Printf("Imports: %v\n", entryPoint.Imports)
}
// Get all entry points (for multi-page apps)
entries := manifest.GetEntryPoints()
for _, entry := range entries {
fmt.Printf("\nEntry: %s\n", entry.Src)
// Generate CSS tags
css := manifest.GenerateCSS(entry.Src, "/assets")
fmt.Printf("CSS tags: %s\n", css)
// Generate module script tags
modules := manifest.GenerateModules(entry.Src, "/assets")
fmt.Printf("Module tags: %s\n", modules)
// Generate preload tags
preloads := manifest.GeneratePreloadModules(entry.Src, "/assets")
fmt.Printf("Preload tags: %s\n", preloads)
}
// Get specific chunk by name
chunk, ok := manifest.GetChunk("src/components/Dashboard.tsx")
if ok {
fmt.Printf("\nChunk found: %s -> %s\n", chunk.Src, chunk.File)
fmt.Printf("Is dynamic entry: %v\n", chunk.IsDynamicEntry)
}
}
```
--------------------------------
### Inject Custom Scripts into Request Context (Go)
Source: https://context7.com/olivere/vite/llms.txt
The `ScriptsToContext` function allows injecting custom JavaScript code or script tags directly into the request context. This is useful for adding third-party scripts like analytics, custom configurations, or page-specific JavaScript logic. The function accepts a string containing the script HTML.
```go
package main
import (
"fmt"
"net/http"
"github.com/olivere/vite"
)
func dashboardHandler(viteHandler *vite.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Inject multiple scripts: analytics, config, and custom initialization
scripts := "
"
ctx = vite.ScriptsToContext(ctx, scripts)
viteHandler.ServeHTTP(w, r.WithContext(ctx))
}
}
```