vite-plugin-go-template
v0.0.1
Published
Vite plugin for Go template integration
Readme
vite-plugin-go-template
Vite plugin for Go template integration with HMR support.
Installation
pnpm add -D vite-plugin-go-templateQuick Start
Vite Config
// vite.config.ts
import { defineConfig } from 'vite'
import goTemplate, { clean } from 'vite-plugin-go-template'
export default defineConfig({
plugins: [
clean(),
goTemplate({
entrypointsDir: 'frontend/entrypoints',
snippetFile: 'vite-tag.html',
snippetDir: 'templates/layouts',
sourceCodeDir: 'frontend',
themeRoot: './'
})
],
build: { emptyOutDir: false }
})Go Server
import (
"html/template"
"github.com/Masterminds/sprig/v3"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
funcMap := sprig.FuncMap()
tmpl := template.Must(
template.New("").Funcs(funcMap).ParseGlob("templates/**/*.html"),
)
router.SetHTMLTemplate(tmpl)
router.Static("/assets", "./assets")
router.Run(":8080")
}Templates
<!-- templates/includes/page.html -->
{{define "content"}}
{{ template "vite-tag" dict "FileUrl" "theme.css" "IsCss" true }}
{{ template "vite-tag" dict "FileUrl" "index.tsx" }}
{{end}}Run
pnpm dev # Terminal 1: Vite dev server
go run main.go # Terminal 2: Go serverUsage
Load Entry Points
{{/* JavaScript/TypeScript */}}
{{ template "vite-tag" dict "FileUrl" "app.tsx" }}
{{/* CSS */}}
{{ template "vite-tag" dict "FileUrl" "theme.css" "IsCss" true }}
{{/* Preload CSS */}}
{{ template "vite-tag" dict "FileUrl" "critical.css" "IsCss" true "PreloadStylesheet" true }}Template Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| FileUrl | string | ✓ | Entry point file path |
| IsCss | boolean | ✗ | Set true for CSS files |
| PreloadStylesheet | boolean | ✗ | Preload stylesheet |
Configuration
Plugin Options
| Option | Default | Description |
|--------|---------|-------------|
| entrypointsDir | 'frontend/entrypoints' | Entry points directory |
| snippetDir | 'snippet' | Snippet output directory |
| snippetFile | 'vite-tag.html' | Snippet filename |
| sourceCodeDir | 'frontend' | Frontend source directory |
| themeRoot | './' | Templates root directory |
| assetPath | '/assets' | Production asset path |
| additionalEntrypoints | [] | Additional entry globs |
Examples
Troubleshooting
HMR not working
- Ensure Vite dev server is running on port 5173
- Check that
vite-tag.htmlwas generated
Assets not loading in production
- Run
pnpm buildbefore starting Go server - Ensure Go server serves
/assetsdirectory
