Skip to content

🔥 Easier and better experience writing Cloudflare workers in Vite

License

Notifications You must be signed in to change notification settings

Aslemammad/vite-plugin-cloudflare

Repository files navigation

vite-plugin-cloudflare 🔥

Vite-plugin-cloudflare is a plugin for transforming & bundling cloudflare workers with shimming modern node polyfills like process, os, stream and other node global functions and modules using Esbuild and Vite!

  • Universal Vite plugin
  • Lightning builds
  • Workers compatible build using shimming
  • Fast development and HMR compatible reloads
  • Builtin Miniflare support

Install

npm i --save-dev vite-plugin-cloudflare esbuild@latest

Plugin

// vite.config.js
import { defineConfig } from "vite";
import vpc from "vite-plugin-cloudflare";

export default defineConfig({
  plugins: [vpc({ scriptPath: "./worker/index.ts" })],
});

The plugin gets an options object with this type signature.

export type Options = {
  // miniflare specific options for development (optional)
  miniflare?: Omit<MiniflareOptions, "script" | "watch">;
  // the worker file (required)
  scriptPath: string;
  // customize globals that need to polyfilled (process, setTimeout, ...)
  polyfilledGlobals?: PolyfilledGlobals;
  // customize mods (node's builtinModules) that need to polyfilled (utils, http, ...)
  polyfilledModules?: PolyfilledModules;
  // a fast-glob pattern for files who's changes should reload the worker (optional)
  workerFilesPattern?: string | string[];
  // enable modules (esm)
  modules?: boolean;
};

Since this plugin works with Esbuild, options passed to the esbuild field of your vite plugin will affect the worker result, unless they are not compatible with the BuildOptions type of Esbuild.

Development

You can start your Vite dev server and continue developing your applications. As previously mentioned, this plugin integrates Miniflare with Vite, so you'd have a nice experience writing your workers.

 vite dev

Build

When building, the plugin is going to start bundling your worker at the end of the vite bundling phase and generates it into the config.outDir with the worker.js file name.

 vite build

Output:

vite v3.0.4 building for production...
✓ 6 modules transformed.
dist/assets/typescript.f6ead1af.svg   1.40 KiB
dist/index.html                       0.44 KiB
dist/assets/index.2547d205.js         1.41 KiB / gzip: 0.72 KiB
dist/assets/index.d0964974.css        1.19 KiB / gzip: 0.62 KiB
🔥 [cloudflare] bundled worker file in 'dist/worker.js'

Wrangler

Update your wrangler config to be compatible with the build, for instance, here's a config that uses the dist/worker.js bundled worker file generated by vite-plugin-cloudflare and serves the assets from the vite build:

# wrangler.toml
name = "vite-ssr-worker"
main = "./dist/worker.js"
compatibility_date = "2022-08-10"

[site]
bucket = "./dist/client"

The values may change based on your build

Skip Requests

Vite has some builtin middlewares that handle different types of requests from the client, and in a Vite plugin, we can inject our middlewares along vite ones.

Vite-plugin-cloudflare injects a middleware, that is responsible for handling the worker, So every request from the client (browser) may come to your worker first, before vite native middlewares. These requests can be assets, transforms and other types of vite-related requests that should not be handled by vite-plugin-cloudflare and instead, they should be handled by vite.

This concern only occurs in dev mode, so no worries when building for production

Here's how we handle these type of requests in vite-plugin-cloudflare.

addEventListener("fetch", (event) => {
  const { pathname } = new URL(url);
  if (pathname.startsWith("/api")) {
    event.respondWith(handleFetchEvent(event));
    return;
  }
  event.respondWith(
    new Response("", {
      headers: {
        "x-skip-request": "",
      },
    })
  );
});

The x-skip-request header enforces vite-plugin-cloudflare to skip the response of the worker and passes the request to the next vite middleware, so Vite would handle the request instead.

Authors


Mohammad Bagher

Contributing

Feel free to create issues/discussions and then PRs for the project!

Sponsors

Your sponsorship can make a huge difference in continuing our work in open source!