major: build islands + scan routeDir without importing user code (#3122)

This fixes a bunch of long standing issues in our tracker where a build
wouldn't finish because of importing user code. It's common for backend
apps to spawn some open ended tasks like subscribing to Deno KV or other
things. This addresses another problem of having to set up ENV vars just
for the build, even though they are technically not required to build
islands.

This also gives a roughly ~30% performance boost on cold starts (at
least on `deno.com`). Unfortunately, this does require some breaking
changes. But I believe the performance improvements + removing the
footgun of loading user code during build is well worth it. This work is
also a precursor in case we want to exploring moving to vite at some
point in the future.

## Breaking changes

1. Build options have moved to the builder.
```diff
  // main.ts
- const app = new App({ build: { outDir: "dist/" } })
+ const app = new App()

  // dev.ts
- const builder = new Builder();
+ const builder = new Builder({ outDir: "dist/" });
```

2. Another breaking change is how file based routes are loaded. Since
they're prepared and loaded by the builder the API changed.

```diff
  // main.ts
  const app = new App()
    .use(staticFiles())
  
- await fsRoutes(app, {
-   loadIsland: (path) => import(`./islands/${path}`),
-   loadRoute: (path) => import(`./routes/${path}`),
- }); 
+ app.fsRoutes()
```
You can optionally change the `islandDir` or `routeDir` by passing that
to the `Builder`:

```ts
// dev.ts
const builder = new Builder({
  islandDir: "/path/to/islands", 
  routeDir: "/path/to/routes"
});
```

3. Import `app` lazily in `dev.ts`. Passing `app` to `builder.build()`
is not necessary anymore.

```diff
- import { app } from "./main.ts";

  const builder = new Builder({ target: "safari12" });
  
  if (Deno.args.includes("build")) {
-    await builder.build(app);
+    await builder.build();
  } else {
-   await builder.listen(app);
+   await builder.listen(() => import("./main.ts"));
  }
```

4. The production run command has changed. It's now using `deno serve`
```diff
  // deno.json
  {
    "tasks": {
      "dev": "deno run -A --watch=static/,routes/ dev.ts",
      "dev": "deno run -A dev.ts build",
-     "start": "deno run -A main.ts",
+     "start": "deno serve -A _fresh/server.js",
    }
  }
```
Remove this bit in `main.ts`:

```diff
  // main.ts
  
- if (import.meta.main) {
-   await app.listen()
- }
```

Fixes https://github.com/denoland/fresh/issues/2240
Fixes https://github.com/denoland/fresh/issues/2640
Fixes https://github.com/denoland/fresh/issues/2592
Fixes https://github.com/denoland/fresh/issues/1843
This commit is contained in:
Marvin Hagemeister
2025-07-24 15:04:05 +02:00
committed by GitHub
parent 69af00ef65
commit 118242eaa6
54 changed files with 1911 additions and 1770 deletions
+22 -57
View File
@@ -1,7 +1,6 @@
import { expect } from "@std/expect";
import { App, getIslandRegistry, setBuildCache } from "./app.ts";
import { App } from "./app.ts";
import { FakeServer } from "./test_utils.ts";
import { ProdBuildCache } from "./build_cache.ts";
import { HttpError } from "./error.ts";
Deno.test("App - .use()", async () => {
@@ -261,6 +260,27 @@ Deno.test("App - .mountApp() compose apps", async () => {
expect(await res.text()).toEqual("A");
});
Deno.test("App - .mountApp() compose apps with .route()", async () => {
const innerApp = new App<{ text: string }>()
.use((ctx) => {
ctx.state.text = "A";
return ctx.next();
})
.route("/", { handler: (ctx) => new Response(ctx.state.text) });
const app = new App<{ text: string }>()
.get("/", () => new Response("ok"))
.mountApp("/foo", innerApp);
const server = new FakeServer(app.handler());
let res = await server.get("/");
expect(await res.text()).toEqual("ok");
res = await server.get("/foo");
expect(await res.text()).toEqual("A");
});
Deno.test("App - .mountApp() self mount, no middleware", async () => {
const innerApp = new App<{ text: string }>()
.use((ctx) => {
@@ -458,30 +478,6 @@ Deno.test("App - catches errors", async () => {
expect(thrownErr).toBeInstanceOf(Error);
});
// TODO: Find a better way to test this
Deno.test.ignore("App - finish setup", async () => {
const app = new App<{ text: string }>()
.get("/", (ctx) => {
return ctx.render(<div>ok</div>);
});
setBuildCache(
app,
await ProdBuildCache.fromSnapshot({
...app.config,
build: {
outDir: "foo",
},
}, getIslandRegistry(app).size),
);
const server = new FakeServer(app.handler());
const res = await server.get("/");
const text = await res.text();
expect(text).toContain("Finish setting up");
expect(res.status).toEqual(500);
});
Deno.test("App - sets error on context", async () => {
const thrown: [unknown, unknown][] = [];
const app = new App()
@@ -545,37 +541,6 @@ Deno.test("App - throw when middleware returns no response", async () => {
expect(text).toContain("Internal server error");
});
Deno.test("App - adding Island should convert to valid export names", () => {
const app = new App();
const islands = getIslandRegistry(app);
const component1 = () => <>OK</>;
const component2 = () => <>OK</>;
const component3 = () => <>OK</>;
app.island("/islands/foo.v2.tsx", "default", component1);
app.island("/islands/_bar-baz-...-$.tsx", "default", component2);
app.island("/islands/1_hello.tsx", "default", component3);
expect(islands.get(component1)!).toEqual({
file: "/islands/foo.v2.tsx",
name: "foo_v2",
exportName: "default",
fn: component1,
});
expect(islands.get(component2)!).toEqual({
file: "/islands/_bar-baz-...-$.tsx",
name: "_bar_baz_$",
exportName: "default",
fn: component2,
});
expect(islands.get(component3)!).toEqual({
file: "/islands/1_hello.tsx",
name: "_hello",
exportName: "default",
fn: component3,
});
});
Deno.test("App - overwrite default 404 handler", async () => {
const app = new App()
.notFound(() => new Response("bar", { status: 404 }))