feat: add config option to disable runtime js (#36)

The config option can be toggled per page:

```js
export const config: PageConfig = { runtimeJS: false };
```
This commit is contained in:
Luca Casonato
2021-06-13 00:01:59 +02:00
committed by GitHub
parent ae4603c731
commit 65d164d073
9 changed files with 66 additions and 20 deletions
+6 -3
View File
@@ -15,13 +15,16 @@ Fresh does not have a build step - you write your code, deploy it to
the framework. the framework.
- No build step - No build step
- Zero config - Zero config necessary
- JIT rendering on the edge - JIT rendering on the edge
- Tiny (example is 3KB of JS) - Tiny (example is 0-3KB of runtime JS)<sup>1</sup>
- Client side hydration - Optional client side hydration
- TypeScript out of the box - TypeScript out of the box
- File-system routing à la Next.js - File-system routing à la Next.js
_<sup>1</sup> Client side hydration can be disabled per page. This results in
**no JS** being shipped to the client._
## Install ## Install
To install, run the following command. This will add `fresh` CLI to your PATH. To install, run the following command. This will add `fresh` CLI to your PATH.
+3 -1
View File
@@ -1,4 +1,4 @@
import { h, PageProps, useData } from "../../deps.ts"; import { h, PageConfig, PageProps, useData } from "../../deps.ts";
export default function ModuleInfoPage({ params }: PageProps) { export default function ModuleInfoPage({ params }: PageProps) {
const module = params.module; const module = params.module;
@@ -32,3 +32,5 @@ async function fetcher(url: string): Promise<ModuleInfo | null> {
if (resp.status === 200) return resp.json(); if (resp.status === 200) return resp.json();
return null; return null;
} }
export const config: PageConfig = { runtimeJS: false };
+13
View File
@@ -1,3 +1,16 @@
export interface PageProps { export interface PageProps {
params: Record<string, string | string[]>; params: Record<string, string | string[]>;
} }
export interface PageConfig {
/**
* Setting this flag to `false` disables all client side runtime JS. This
* means that all interactivity on the client that depends on Preact or other
* JS code will not function. This option is set to `true` (runtime javascript
* is enabled) by default.
*
* It is recommended to disable runtime JavaScript for static pages that do
* not require interactivity, like marketing or blog pages.
*/
runtimeJS?: boolean;
}
+12 -11
View File
@@ -1,12 +1,10 @@
import { extname, mediaTypeLookup, router } from "./deps.ts"; import { extname, mediaTypeLookup, router } from "./deps.ts";
import * as rt from "../runtime/deps.ts";
import { PageProps } from "../runtime/types.ts";
import { Routes } from "./mod.ts"; import { Routes } from "./mod.ts";
import { Bundler } from "./bundle.ts"; import { Bundler } from "./bundle.ts";
import { INTERNAL_PREFIX } from "./constants.ts"; import { INTERNAL_PREFIX } from "./constants.ts";
import { JS_PREFIX } from "./constants.ts"; import { JS_PREFIX } from "./constants.ts";
import { BUILD_ID } from "./constants.ts"; import { BUILD_ID } from "./constants.ts";
import { ApiRoute, Page } from "./types.ts"; import { ApiRoute, ApiRouteModule, Page, PageModule } from "./types.ts";
import { render } from "./render.tsx"; import { render } from "./render.tsx";
export class ServerContext { export class ServerContext {
@@ -40,23 +38,26 @@ export class ServerContext {
const route = pathToRoute(baseRoute); const route = pathToRoute(baseRoute);
const name = baseRoute.replace("/", "-"); const name = baseRoute.replace("/", "-");
if (path.startsWith("/api/")) { if (path.startsWith("/api/")) {
const handlers = Object.fromEntries(
Object.entries(module as ApiRouteModule).filter(([method]) =>
method === "default" || router.METHODS.includes(method)
),
);
const apiRoute: ApiRoute = { const apiRoute: ApiRoute = {
route, route,
url, url,
name, name,
handlers: Object.fromEntries( handlers,
Object.entries(module).filter(([method]) =>
router.METHODS.includes(method) || method === "default"
),
),
}; };
apiRoutes.push(apiRoute); apiRoutes.push(apiRoute);
} else if (!path.startsWith("/_")) { } else if (!path.startsWith("/_")) {
const { default: component, config } = (module as PageModule);
const page: Page = { const page: Page = {
route, route,
url, url,
name, name,
component: module.default as rt.ComponentType<PageProps>, component,
runtimeJS: config?.runtimeJS ?? true,
}; };
pages.push(page); pages.push(page);
} }
@@ -83,8 +84,8 @@ export class ServerContext {
); );
const body = await render({ const body = await render({
page, page,
imports, imports: page.runtimeJS ? imports : [],
preloads, preloads: page.runtimeJS ? preloads : [],
params: match.params, params: match.params,
}); });
return new Response(body, { return new Response(body, {
+4
View File
@@ -53,6 +53,10 @@ export async function render(opts: RenderOptions): Promise<string> {
templateProps = undefined; templateProps = undefined;
} }
if (opts.imports.length === 0) {
templateProps = undefined;
}
const html = template({ const html = template({
bodyHtml, bodyHtml,
imports: opts.imports, imports: opts.imports,
+3 -1
View File
@@ -1,9 +1,10 @@
import { ComponentType } from "../runtime/deps.ts"; import { ComponentType } from "../runtime/deps.ts";
import { router } from "./deps.ts"; import { router } from "./deps.ts";
import { PageProps } from "../runtime/types.ts"; import { PageConfig, PageProps } from "../runtime/types.ts";
export interface PageModule { export interface PageModule {
default: ComponentType<PageProps>; default: ComponentType<PageProps>;
config?: PageConfig;
} }
export interface Page { export interface Page {
@@ -11,6 +12,7 @@ export interface Page {
url: string; url: string;
name: string; name: string;
component: ComponentType<PageProps>; component: ComponentType<PageProps>;
runtimeJS: boolean;
} }
export type ApiRouteModule = { export type ApiRouteModule = {
+7
View File
@@ -0,0 +1,7 @@
import { h, PageConfig } from "../deps.ts";
export default function StaticPage() {
return <p>This is a static page.</p>;
}
export const config: PageConfig = { runtimeJS: false };
+6 -4
View File
@@ -2,17 +2,19 @@
// This file SHOULD be checked into source version control. // This file SHOULD be checked into source version control.
// To update this file, run `fresh routes`. // To update this file, run `fresh routes`.
import * as $0 from "./pages/index.tsx"; import * as $0 from "./pages/api/name.ts";
import * as $1 from "./pages/api/get_only.ts"; import * as $1 from "./pages/api/get_only.ts";
import * as $2 from "./pages/api/name.ts"; import * as $2 from "./pages/static.tsx";
import * as $3 from "./pages/[name].tsx"; import * as $3 from "./pages/[name].tsx";
import * as $4 from "./pages/index.tsx";
const routes = { const routes = {
pages: { pages: {
"./pages/index.tsx": $0, "./pages/api/name.ts": $0,
"./pages/api/get_only.ts": $1, "./pages/api/get_only.ts": $1,
"./pages/api/name.ts": $2, "./pages/static.tsx": $2,
"./pages/[name].tsx": $3, "./pages/[name].tsx": $3,
"./pages/index.tsx": $4,
}, },
baseUrl: import.meta.url, baseUrl: import.meta.url,
}; };
+12
View File
@@ -85,3 +85,15 @@ Deno.test("/api/xyz not found", async () => {
assert(resp); assert(resp);
assertEquals(resp.status, 404); assertEquals(resp.status, 404);
}); });
Deno.test("/static page prerender", async () => {
const resp = await router(new Request("https://fresh.deno.dev/static"));
assert(resp);
assertEquals(resp.status, 200);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
assert(!body.includes(`static.js`));
assert(!body.includes(`</script>`));
assertStringIncludes(body, "<p>This is a static page.</p>");
assert(!body.includes("__FRSH_PROPS"));
});