Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/olivere/vite

Vite backend integration for Go
https://github.com/olivere/vite

Last synced: about 2 months ago
JSON representation

Vite backend integration for Go

Awesome Lists containing this project

README

        

# Vite Backend integration with Go

> **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](https://vitejs.dev/guide/backend-integration.html) 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:

```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
})
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
//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 { ... }
```

## Example

See the [`example` directory](https://github.com/olivere/vite/tree/main/example) for a demonstration.

## License

See license in LICENSE file.