@hiogawa/node-loader-cloudflare
v0.0.2
Published
This package provides [Node.js custom loaders](https://nodejs.org/api/module.html#customization-hooks) to enable `cloudflare:workers` imports based on [Wrangler platform proxy](https://developers.cloudflare.com/workers/wrangler/api/#getplatformproxy) on N
Downloads
6,626
Readme
@hiogawa/node-loader-cloudflare
This package provides Node.js custom loaders to enable cloudflare:workers imports based on Wrangler platform proxy on Node.js.
import { env, waitUntil } from "cloudflare:workers";
await env.KV.get("some-key");
waitUntil(someTask());This allows Vite SSR application to seamlessly access Cloudflare Workers runtime APIs during both development and deployment when the framework doesn't have a support of @cloudflare/vite-plugin.
Installation
npm install @hiogawa/node-loader-cloudflare wranglerUsage
Add the plugin to your Vite configuration:
import { defineConfig } from "vite";
import nodeLoaderCloudflare from "@hiogawa/node-loader-cloudflare/vite";
export default defineConfig({
plugins: [
// see jsdoc for available options
nodeLoaderCloudflare({
// getPlatformProxyOptions: { ... }
// environments: [...],
// build: true,
// exposeGlobals: true,
}),
],
});Or you can directly register the loader via:
import { registerCloudflare } from "@hiogawa/node-loader-cloudflare";
registerCloudflare();How it works
This plugin uses Node.js custom loaders to intercept imports of cloudflare:workers and provide a runtime implementation:
- Node Loader Registration: The plugin registers a custom Node.js loader that intercepts module resolution and loading
- Platform Proxy: It initializes Wrangler's
getPlatformProxy()which provides local implementations of Cloudflare Workers runtime APIs - Module Interception: When code imports
cloudflare:workers, the loader returns a synthetic module that exposes runtime APIs likeenvandwaitUntil - Lifecycle Management: The loader is registered during Vite's build start and deregistered on build end to ensure proper cleanup
This allows you to:
- Import
cloudflare:workersmodules in your Vite application - Access Cloudflare Workers runtime environment (
env,waitUntil, etc.) in dev server and optionally during build - Use bindings like KV, D1, R2, etc. in your local environment
- Optionally expose Cloudflare globals like
WebSocketPairandcachestoglobalThis
Example
License
MIT
