Note This library is still a work in progress and may not be stable or fully functional. Use it at your own risk.
This library implements a Vite backend integration for Go. Please follow the guidelines there to configure your Vite project, i.e. vite.config.(js|ts)
. E.g. you need to make sure that the manifest.json
is being generated for production.
The integration is done by a HTTP handler, implementing http.Handler
. The handler has two modes: Development and production.
In development mode, you need to create the handler by passing a file system that points to a source of your Vite app as the first parameter. The second parameter needs to be true to put the handler into development mode. And the third and last parameter points to the Vite server running in the background, typically http://localhost:5173
(the endpoint served by running npm run dev
, pnpm dev
etc.). Again: You need to run the Vite server in the background in development mode, so open up a 2nd console and run something like npm run dev
.
Example:
// 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
})
if err != nil { ... }
In production mode, you typically embed the whole generated dist directory generated by vite build
into the Go binary, using go:embed
. In that case, your first parameter needs to be the embedded "dist" file system. The second parameter must be false to enable production mode. The last parameter can be blank, as it is not used in production mode.
Example:
//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 { ... }
See the examples/basic
directory for a demonstration of a very basic React app that integrates a Go backend.
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.
You can use custom HTML templates in your Go backend for serving different React pages. See the examples/template-registry
directory for an example.
See license in LICENSE file.