Skip to content

W4G1/vite-plugin-protobuf

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

49 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

vite-plugin-protobuf

A Vite plugin that compiles .proto files using protoc and @protobuf-ts to generate TypeScript clients, ready for use in your frontend app.

  • Powered by protobuf-ts
  • The plugin watches your .proto files and regenerates output on changes
  • All generated files are written to node_modules/.vite/proto-gen
  • You can access this output using the alias @proto-gen

Installation

Install the plugin:

npm install --save-dev vite-plugin-protobuf

Required Dependencies

You must manually add the following dependencies to your package.json:

{
  "dependencies": {
    "@protobuf-ts/runtime": "^2.9.6",
    "@protobuf-ts/runtime-rpc": "^2.9.6"
  },
  "devDependencies": {
    "@protobuf-ts/plugin": "^2.9.6",
    "@protobuf-ts/protoc": "^2.9.6",
  }
}

Then run:

npm install

Configuration

Add the plugin to your vite.config.ts or vite.config.js:

import protobuf from 'vite-plugin-protobuf';

export default {
  plugins: [
    protobuf({
      protoPath: '../proto'
    })
  ]
};

Usage with Vite + SPA (React, Vue, Svelte etc.)

Update your tsconfig.app.json (or equivalent) with the following path alias:

{
  "compilerOptions": {
    "paths": {
      "@proto-gen/*": [
        "./node_modules/.vite/proto-gen/*"
      ]
    }
  }
}

This ensures TypeScript can resolve the generated files.


Usage with SvelteKit

Modify the vite.config.ts like so:

import protobuf from 'vite-plugin-protobuf';

export default {
  plugins: [
    protobuf({
      protoPath: "../proto",
      outputDir: "./src/lib/proto",
    })
  ]
};

Once your .proto files are compiled, you can import the generated clients like so:

// Compiled from helloworld.proto
import { GreeterClient } from "$lib/proto/helloworld.client";

Next steps with gRPC Web

To use the generated clients with gRPC over HTTP in the browser, install:

npm install @protobuf-ts/grpcweb-transport

Then, create your gRPC client like this:

import { GreeterClient } from "@proto-gen/helloworld.client";
import { GrpcWebFetchTransport } from "@protobuf-ts/grpcweb-transport";

const transport = new GrpcWebFetchTransport({
  baseUrl: "https://your-grpc-api.com"
});

const client = new GreeterClient(transport);

async function greet() {
  const response = await client.sayHello({ name: "World" });
  console.log(response.response.message);
}

The GrpcWebFetchTransport provides a browser-friendly implementation of the gRPC-web protocol using standard fetch.

For more information, see protobuf-ts.

About

⚡📄 Vite plugin that automatically compiles .proto files to TypeScript clients

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published