Skip to content

Commit

Permalink
fix: undefined fallback fetch on watch update with pages dev
Browse files Browse the repository at this point in the history
Subsequent Pages Functions worker builds due to file changes were
not replacing `__FALLBACK_SERVICE_FETCH__` leading to
`ReferenceError`s. This change switches to using `esbuild`'s built-in
`define` option, instead of `esbuild-plugin-replace`, removing an
additional dependency.
  • Loading branch information
mrbbot committed Jan 8, 2022
1 parent def1468 commit 41d6df0
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 53 deletions.
44 changes: 0 additions & 44 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/wrangler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
],
"dependencies": {
"esbuild": "0.14.1",
"esbuild-plugin-replace": "^1.1.0",
"miniflare": "2.0.0",
"path-to-regexp": "^6.2.0",
"semiver": "^1.1.0"
Expand Down
9 changes: 3 additions & 6 deletions packages/wrangler/pages/functions/buildWorker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import path from "path";
import { build } from "esbuild";
import { replace } from "esbuild-plugin-replace";

type Options = {
routesModule: string;
Expand Down Expand Up @@ -34,12 +33,10 @@ export function buildWorker({
sourcemap,
watch,
allowOverwrite: true,
define: {
__FALLBACK_SERVICE__: JSON.stringify(fallbackService),
},
plugins: [
replace({
__FALLBACK_SERVICE_FETCH__: fallbackService
? `env.${fallbackService}.fetch`
: "fetch",
}),
{
name: "wrangler notifier and monitor",
setup(pluginBuild) {
Expand Down
9 changes: 7 additions & 2 deletions packages/wrangler/pages/functions/template-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ type RouteHandler = {

// inject `routes` via ESBuild
declare const routes: RouteHandler[];
// define `__FALLBACK_SERVICE__` via ESBuild
declare const __FALLBACK_SERVICE__: string;

// expect an ASSETS fetcher binding pointing to the asset-server stage
type Env = {
Expand Down Expand Up @@ -89,8 +91,11 @@ function* executeRequest(request: Request, env: Env) {

// Finally, yield to the fallback service (`env.ASSETS.fetch` in Pages' case)
return {
// @ts-expect-error we don't define a type for the special global __FALLBACK_SERVICE_FETCH__ since we replace it when we're building anyway
handler: () => __FALLBACK_SERVICE_FETCH__(request.url, request),
handler: () =>
__FALLBACK_SERVICE__
? // @ts-expect-error expecting __FALLBACK_SERVICE__ to be the name of a service binding, so fetch should be defined
env[__FALLBACK_SERVICE__].fetch(request)
: fetch(request),
params: {} as Params,
};
}
Expand Down

0 comments on commit 41d6df0

Please sign in to comment.