Skip to content

Commit

Permalink
use the new resolve.builtins vite config to specify the cloudflare …
Browse files Browse the repository at this point in the history
…and node builtins

and remove the ad-hoc `cloudflare:` handling logic
  • Loading branch information
dario-piotrowicz committed Dec 3, 2024
1 parent 66a00f9 commit add5aa8
Show file tree
Hide file tree
Showing 5 changed files with 143 additions and 421 deletions.
9 changes: 2 additions & 7 deletions packages/vite-plugin-cloudflare/src/cloudflare-environment.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { builtinModules } from 'node:module';
import * as path from 'node:path';
import * as vite from 'vite';
import { getNodeCompatExternals } from './node-js-compat';
Expand Down Expand Up @@ -134,6 +133,7 @@ export function createCloudflareEnvironmentOptions(
noExternal: true,
// We want to use `workerd` package exports if available (e.g. for postgres).
conditions: ['workerd', 'module', 'browser', 'development|production'],
builtins: [...cloudflareBuiltInModules],
},
dev: {
createEnvironment(name, config) {
Expand All @@ -155,17 +155,12 @@ export function createCloudflareEnvironmentOptions(
input: userConfig.root
? path.resolve(userConfig.root, options.main)
: path.resolve(options.main),
external: [...cloudflareBuiltInModules, ...getNodeCompatExternals()],
external: [...getNodeCompatExternals()],
},
},
optimizeDeps: {
// Note: ssr pre-bundling is opt-in, and we need to enabled it by setting noDiscovery to false
noDiscovery: false,
exclude: [
...cloudflareBuiltInModules,
// we have to exclude all node modules to work in dev-mode not just the unenv externals...
...builtinModules.concat(builtinModules.map((m) => `node:${m}`)),
],
esbuildOptions: {
platform: 'neutral',
resolveExtensions: [
Expand Down
40 changes: 40 additions & 0 deletions packages/vite-plugin-cloudflare/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as fs from 'node:fs';
import { builtinModules } from 'node:module';
import path from 'node:path';
import { createMiddleware } from '@hattip/adapter-node';
import { Miniflare } from 'miniflare';
Expand All @@ -15,6 +16,7 @@ import {
import {
getNodeCompatAliases,
injectGlobalCode,
isNodeCompat,
resolveNodeAliases,
} from './node-js-compat';
import { normalizePluginConfig } from './plugin-config';
Expand Down Expand Up @@ -96,6 +98,9 @@ export function cloudflare<T extends Record<string, WorkerOptions>>(
pluginConfig,
resolvedConfig,
);
Object.keys(normalizedPluginConfig.workers).forEach((name) =>
addNodeBuiltinsIfNeeded(resolvedConfig, name, normalizedPluginConfig),
);
},
async resolveId(source) {
const worker = normalizedPluginConfig.workers[this.environment.name];
Expand Down Expand Up @@ -206,3 +211,38 @@ export function cloudflare<T extends Record<string, WorkerOptions>>(
},
};
}

/**
* Adds to the worker resolved configuration the necessary node builtin config options if the worker is under nodejs compat
*
* @param resolvedConfig the vite resolved config (that will be side-effectfully updated)
* @param name the name of the worker
* @param normalizedPluginConfig the normalized/resolved plugin config
*/
function addNodeBuiltinsIfNeeded(
resolvedConfig: vite.ResolvedConfig,
name: string,
normalizedPluginConfig: NormalizedPluginConfig,
) {
invariant(
resolvedConfig.environments[name] && normalizedPluginConfig.workers[name],
`environment configs for worker "${name}" not found`,
);

const nodeCompat = isNodeCompat(
normalizedPluginConfig.workers[name].workerOptions,
);

const nodeCompatModules = nodeCompat
? [...builtinModules.concat(builtinModules.map((m) => `node:${m}`))]
: [];

resolvedConfig.environments[name].resolve.builtins = [
...resolvedConfig.environments[name].resolve.builtins,
...nodeCompatModules,
];
resolvedConfig.environments[name].optimizeDeps.exclude = [
...(resolvedConfig.environments[name].optimizeDeps.exclude ?? []),
...nodeCompatModules,
];
}
11 changes: 0 additions & 11 deletions packages/vite-plugin-cloudflare/src/miniflare-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,17 +322,6 @@ export function getDevMiniflareOptions(

const [moduleId] = invokePayloadData.data;

// For some reason we need this here for cloudflare built-ins (e.g. `cloudflare:workers`) but not for node built-ins (e.g. `node:path`)
// See https://github.com/flarelabs-net/vite-plugin-cloudflare/issues/46
if (moduleId.startsWith('cloudflare:')) {
const result = {
externalize: moduleId,
type: 'builtin',
} satisfies vite.FetchResult;

return new MiniflareResponse(JSON.stringify({ r: result }));
}

// Sometimes Vite fails to resolve built-ins and converts them to "url-friendly" ids
// that start with `/@id/...`.
if (moduleId.startsWith('/@id/')) {
Expand Down
Loading

0 comments on commit add5aa8

Please sign in to comment.