npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vite-plugin-cloudflare-functions

v0.6.1

Published

Make Cloudflare Pages Functions works with Vite friendly

Downloads

167

Readme

vite-plugin-cloudflare-functions

version CI miki

Make Cloudflare Pages Functions works with Vite friendly.

Features

When should you use this plugin?

  • If it is not necessary to use a heavy SSR framework like nuxt
  • If your application is a static SPA, but you also want to write several API endpoints

If you have used some meta SSR framework like nuxt, there is no need to use this plugin. But if you want to add some API endpoints to your SPA, just use it.

This plugin provides some simple utilities to help you develop a SPA with serverless API endpoints powered by Cloudflare Pages Functions.

  • Dev: Automatically start wrangler pages dev server
  • Dev: Automatically generate serverless functions API type declaration
  • Build: Automatically move the functions source directory for monorepo

Installation

npm i -D vite-plugin-cloudflare-functions
// vite.config.ts

import { defineConfig } from 'vite';

import CloudflarePagesFunctions from 'vite-plugin-cloudflare-functions';

export default defineConfig({
  plugins: [
    CloudflarePagesFunctions()
  ]
});

Usage

Functions

Just write pages functions as usual, but you can use the following utility functions to make auto-generation and IDE type inference work.

  • makePagesFunction
  • makeRawPagesFunction
  • makeResponse: create a Response using your JSON object
  • makeRawResponse: same with new Response(...) but wrapped with a generic type used for type inference
// /api/[msg].ts

import {
  makeRawPagesFunction,
  makePagesFunction,
  makeResponse
} from 'vite-plugin-cloudflare-functions/worker';

export const onRequestGet = makePagesFunction(({ params }) => ({
  status: 'OK',
  data: 'Hello, ' + params.msg + '!'
}));

export const onRequestPost = makeRawPagesFunction(({ params }) =>
  makeResponse({
    status: 'OK',
    data: 'Post ' + params.msg + ' OK!'
  })
);

Override environment

For example, you have set the environment variable PASS (you can config it in the plugin option, see Configuration).

// cloudflare.d.ts

/// <reference types="@cloudflare/workers-types" />
/// <reference types="vite-plugin-cloudflare-functions/types" />

import 'vite-plugin-cloudflare-functions/worker';

declare module 'vite-plugin-cloudflare-functions/worker' {
  interface PagesFunctionEnv {
    PASS: string;
  }

  interface PagesFunctionData {}
}

Then you can find the parameter env has corresponding type declarations.

// /api/index.ts

import { makePagesFunction } from 'vite-plugin-cloudflare-functions/worker';

export const onRequestGet = makePagesFunction(({ env }) => ({
  pass: env.PASS
}));

Client

Just write you client code as usual, but for we generate the API endpoint response body type declarations automatically, so that with the provided client useFunctions (powered by axios), your IDE will provide smarter IntelliSense.

// /main.ts
import { useFunctions } from 'vite-plugin-cloudflare-functions/client';

const client = useFunctions();

client.get('/api/world').then((resp) => {
  // The type of resp is { status: string, data: string }
});

Full example is here.

Configuration

// vite.config.ts

import { defineConfig } from 'vite';

import CloudflarePagesFunctions from 'vite-plugin-cloudflare-functions';

export default defineConfig({
  plugins: [
    CloudflarePagesFunctions({
      // Cloudflare Functions root directory
      root: './functions',
      // Copy the functions directory to outDir or do nothing
      outDir: undefined,
      // Generate API type declarations
      dts: './cloudflare.d.ts',
      // Wrangler configuration
      wrangler: {
        // Wrangler dev server port
        port: 8788,
        // Enable wrangler log
        log: true,
        // Bind variable/secret
        binding: {
          KEY: 'VALUE'
        },
        // Bind KV namespace
        kv: [
          'NAMESPACE'
        ],
        // Bind D1 database 
        d1: [
          'D1'
        ],
        // Bind Durable Object
        do: {
          DO: 'DO'
        },
        // Bind R2 bucket
        r2: [
          'BUCKET'
        ]
      }
    })
  ]
});

Note

This plugin starts the wrangler pages dev server under the hood. The configuration field binding, kv, do, d1, r2 are passed to run the command wrangler pages dev to start pages dev server. You can find more information about this command at Commands - Cloudflare Worker docs.

The generated command of the above example is wrangler pages dev --local --ip localhost --port 8788 --proxy <generated by vite dev server> --binding KEY=VALUE --kv NAMESPACE --d1 D1 --do DO=DO --r2 BUCKET.

License

MIT License © 2022 XLor