Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/major-snails-post.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
"@cloudflare/vite-plugin": minor
---

Add support for child environments.

This is to support React Server Components via [@vitejs/plugin-rsc](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-rsc) and frameworks that build on top of it. A `childEnvironments` option is now added to the plugin config to enable using multiple environments within a single Worker. The parent environment can import modules from a child environment in order to access a separate module graph. For a typical RSC use case, the plugin might be configured as in the following example:

```ts
export default defineConfig({
plugins: [
cloudflare({
viteEnvironment: {
name: "rsc",
childEnvironments: ["ssr"],
},
}),
],
});
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { expect, test } from "vitest";
import { getTextResponse, isBuild } from "../../__test-utils__";

test.runIf(!isBuild)("can import module from child environment", async () => {
const response = await getTextResponse();
expect(response).toBe("Hello from the child environment");
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@playground/child-environment",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"check:type": "tsc --build",
"dev": "vite dev",
"preview": "vite preview"
},
"devDependencies": {
"@cloudflare/vite-plugin": "workspace:*",
"@cloudflare/workers-tsconfig": "workspace:*",
"@cloudflare/workers-types": "catalog:default",
"typescript": "catalog:default",
"vite": "catalog:vite-plugin",
"wrangler": "workspace:*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// @ts-expect-error - no types
import { getEnvironmentName } from "virtual:environment-name";

export function getMessage() {
return `Hello from the ${getEnvironmentName()} environment`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
declare global {
// In real world usage, this is accessed by `@vitejs/plugin-rsc`
function __VITE_ENVIRONMENT_RUNNER_IMPORT__(
environmentName: string,
id: string
): Promise<unknown>;
}

export default {
async fetch() {
const childEnvironmentModule = (await __VITE_ENVIRONMENT_RUNNER_IMPORT__(
"child",
"./src/child-environment-module"
)) as { getMessage: () => string };

return new Response(childEnvironmentModule.getMessage());
},
} satisfies ExportedHandler;
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.node.json" },
{ "path": "./tsconfig.worker.json" }
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": ["@cloudflare/workers-tsconfig/base.json"],
"include": ["vite.config.ts", "__tests__"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": ["@cloudflare/workers-tsconfig/worker.json"],
"include": ["src"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"$schema": "http://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"outputs": ["dist/**"]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
plugins: [
cloudflare({
inspectorPort: false,
persistState: false,
viteEnvironment: {
name: "parent",
childEnvironments: ["child"],
},
}),
{
name: "virtual-module-plugin",
resolveId(source) {
if (source === "virtual:environment-name") {
return "\0virtual:environment-name";
}
},
load(id) {
if (id === "\0virtual:environment-name") {
return `export function getEnvironmentName() { return ${JSON.stringify(this.environment.name)} }`;
}
},
},
],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "worker",
"main": "./src/index.ts",
}
77 changes: 52 additions & 25 deletions packages/vite-plugin-cloudflare/src/cloudflare-environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { CoreHeaders } from "miniflare";
import * as vite from "vite";
import { additionalModuleRE } from "./plugins/additional-modules";
import {
ENVIRONMENT_NAME_HEADER,
GET_EXPORT_TYPES_PATH,
INIT_PATH,
IS_ENTRY_WORKER_HEADER,
IS_PARENT_ENVIRONMENT_HEADER,
UNKNOWN_HOST,
VIRTUAL_WORKER_ENTRY,
WORKER_ENTRY_PATH_HEADER,
Expand Down Expand Up @@ -97,15 +99,17 @@ export class CloudflareDevEnvironment extends vite.DevEnvironment {
async initRunner(
miniflare: Miniflare,
workerConfig: ResolvedWorkerConfig,
isEntryWorker: boolean
options: { isEntryWorker: boolean; isParentEnvironment: boolean }
): Promise<void> {
const response = await miniflare.dispatchFetch(
new URL(INIT_PATH, UNKNOWN_HOST),
{
headers: {
[CoreHeaders.ROUTE_OVERRIDE]: workerConfig.name,
[WORKER_ENTRY_PATH_HEADER]: encodeURIComponent(workerConfig.main),
[IS_ENTRY_WORKER_HEADER]: String(isEntryWorker),
[IS_ENTRY_WORKER_HEADER]: String(options.isEntryWorker),
[ENVIRONMENT_NAME_HEADER]: this.name,
[IS_PARENT_ENVIRONMENT_HEADER]: String(options.isParentEnvironment),
upgrade: "websocket",
},
}
Expand Down Expand Up @@ -170,14 +174,6 @@ const defaultConditions = ["workerd", "worker", "module", "browser"];
// workerd uses [v8 version 14.2 as of 2025-10-17](https://developers.cloudflare.com/workers/platform/changelog/#2025-10-17)
const target = "es2024";

const rollupOptions: vite.Rollup.RollupOptions = {
input: {
[MAIN_ENTRY_NAME]: VIRTUAL_WORKER_ENTRY,
},
// workerd checks the types of the exports so we need to ensure that additional exports are not added to the entry module
preserveEntrySignatures: "strict",
};

// TODO: consider removing in next major to use default extensions
const resolveExtensions = [
".mjs",
Expand All @@ -198,15 +194,26 @@ export function createCloudflareEnvironmentOptions({
mode,
environmentName,
isEntryWorker,
isParentEnvironment,
hasNodeJsCompat,
}: {
workerConfig: ResolvedWorkerConfig;
userConfig: vite.UserConfig;
mode: vite.ConfigEnv["mode"];
environmentName: string;
isEntryWorker: boolean;
isParentEnvironment: boolean;
hasNodeJsCompat: boolean;
}): vite.EnvironmentOptions {
const rollupOptions: vite.Rollup.RollupOptions = isParentEnvironment
? {
input: {
[MAIN_ENTRY_NAME]: VIRTUAL_WORKER_ENTRY,
},
// workerd checks the types of the exports so we need to ensure that additional exports are not added to the entry module
preserveEntrySignatures: "strict",
}
: {};
const define = getProcessEnvReplacements(hasNodeJsCompat, mode);

return {
Expand Down Expand Up @@ -323,19 +330,39 @@ export function initRunners(
viteDevServer: vite.ViteDevServer,
miniflare: Miniflare
): Promise<void[]> | undefined {
return Promise.all(
[...resolvedPluginConfig.environmentNameToWorkerMap].map(
([environmentName, worker]) => {
debuglog("Initializing worker:", worker.config.name);
const isEntryWorker =
environmentName === resolvedPluginConfig.entryWorkerEnvironmentName;

return (
viteDevServer.environments[
environmentName
] as CloudflareDevEnvironment
).initRunner(miniflare, worker.config, isEntryWorker);
}
)
);
const initPromises = [
...resolvedPluginConfig.environmentNameToWorkerMap,
].flatMap(([environmentName, worker]) => {
debuglog("Initializing worker:", worker.config.name);
const isEntryWorker =
environmentName === resolvedPluginConfig.entryWorkerEnvironmentName;

const childEnvironmentNames =
resolvedPluginConfig.environmentNameToChildEnvironmentNamesMap.get(
environmentName
) ?? [];

const parentInit = (
viteDevServer.environments[environmentName] as CloudflareDevEnvironment
).initRunner(miniflare, worker.config, {
isEntryWorker,
isParentEnvironment: true,
});

const childInits = childEnvironmentNames.map((childEnvironmentName) => {
debuglog("Initializing child environment:", childEnvironmentName);
return (
viteDevServer.environments[
childEnvironmentName
] as CloudflareDevEnvironment
).initRunner(miniflare, worker.config, {
isEntryWorker: false,
isParentEnvironment: false,
});
});

return [parentInit, ...childInits];
});

return Promise.all(initPromises);
}
52 changes: 42 additions & 10 deletions packages/vite-plugin-cloudflare/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
PreviewResolvedConfig,
ResolvedPluginConfig,
ResolvedWorkerConfig,
Worker,
WorkersResolvedConfig,
} from "./plugin-config";
import type { MiniflareOptions } from "miniflare";
Expand Down Expand Up @@ -141,12 +142,47 @@ export class PluginContext {
return this.#resolvedViteConfig;
}

isChildEnvironment(environmentName: string): boolean {
if (this.resolvedPluginConfig.type !== "workers") {
return false;
}

for (const childEnvironmentNames of this.resolvedPluginConfig.environmentNameToChildEnvironmentNamesMap.values()) {
if (childEnvironmentNames.includes(environmentName)) {
return true;
}
}

return false;
}

#getWorker(environmentName: string): Worker | undefined {
if (this.resolvedPluginConfig.type !== "workers") {
return undefined;
}

const worker =
this.resolvedPluginConfig.environmentNameToWorkerMap.get(environmentName);

if (worker) {
return worker;
}

// Check if this is a child environment and, if so, return the parent's Worker
for (const [parentEnvironmentName, childEnvironmentNames] of this
.resolvedPluginConfig.environmentNameToChildEnvironmentNamesMap) {
if (childEnvironmentNames.includes(environmentName)) {
return this.resolvedPluginConfig.environmentNameToWorkerMap.get(
parentEnvironmentName
);
}
}

return undefined;
}

getWorkerConfig(environmentName: string): ResolvedWorkerConfig | undefined {
return this.resolvedPluginConfig.type === "workers"
? this.resolvedPluginConfig.environmentNameToWorkerMap.get(
environmentName
)?.config
: undefined;
return this.#getWorker(environmentName)?.config;
}

get allWorkerConfigs(): Unstable_Config[] {
Expand All @@ -173,11 +209,7 @@ export class PluginContext {
}

getNodeJsCompat(environmentName: string): NodeJsCompat | undefined {
return this.resolvedPluginConfig.type === "workers"
? this.resolvedPluginConfig.environmentNameToWorkerMap.get(
environmentName
)?.nodeJsCompat
: undefined;
return this.#getWorker(environmentName)?.nodeJsCompat;
}
}

Expand Down
10 changes: 9 additions & 1 deletion packages/vite-plugin-cloudflare/src/miniflare-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
import { getContainerOptions, getDockerPath } from "./containers";
import { getInputInspectorPort } from "./debug";
import { additionalModuleRE } from "./plugins/additional-modules";
import { ENVIRONMENT_NAME_HEADER } from "./shared";
import { withTrailingSlash } from "./utils";
import type { CloudflareDevEnvironment } from "./cloudflare-environment";
import type { ContainerTagToOptionsMap } from "./containers";
Expand Down Expand Up @@ -381,10 +382,17 @@ export async function getDevMiniflareOptions(
}
: {}),
__VITE_INVOKE_MODULE__: async (request) => {
const targetEnvironmentName = request.headers.get(
ENVIRONMENT_NAME_HEADER
);
assert(
targetEnvironmentName,
`Expected ${ENVIRONMENT_NAME_HEADER} header`
);
const payload =
(await request.json()) as vite.CustomPayload;
const devEnvironment = viteDevServer.environments[
environmentName
targetEnvironmentName
] as CloudflareDevEnvironment;
const result =
await devEnvironment.hot.handleInvoke(payload);
Expand Down
Loading
Loading