Ruck
Ruck is an open source buildless React web application framework for Deno. It can be used to create basic sites or powerful apps.
Work with cutting edge standard technologies such as ESM, dynamic imports, HTTP imports, and import maps to avoid build steps like transpilation or bundling. Deno and browsers directly run the source code. Ruck is extremely lean with few dependencies. Modules are focused with default exports that are only deep imported when needed.
Some things that are complicated or impossible with traditional frameworks are easy with Ruck, for exampleā¦
- Matching dynamic routes with RegEx or custom logic. Ideally an invalid slug in a route URL results in a error page without loading the routeās components or data.
- Components can use the
TransferContext
React context during SSR to read the page HTTP request and modify the response. This is surprisingly difficult with Next.js, seenext-server-context
. - Proper React rendering of head tags specified by the
useHead
React hook. React components with a normal lifecycle can be used to render head tags that can be grouped, ordered, and prioritized for overrides. Frameworks like Next.js provide a React component that accepts basic head tags as children that it manually iterates and syncs in the document head DOM. - SSR with component level data fetching. This is quite tricky with frameworks
like Next.js and Remix that support
data fetching at the route level, see
next-graphql-react
. - GraphQL ready to use via React hooks from
graphql-react
. - Declarative system for auto loading and unloading component CSS file dependencies with absolute or relative URLs.
- Baked-in type safety and IntelliSense via TypeScript JSDoc comments.
Installation
A Ruck project contains:
Import map JSON files that tell your IDE, Deno, and browsers where to import dependencies from. Ruck automatically uses
es-module-shims
so you donāt need to worry about poor browser support for import maps.Ideally use separate development and production import maps for the server and client. This way a version of React that has more detailed error messages can be used during local development, and server specific dependencies can be excluded from the browser import map for a faster page load.
Recommended import map file names and starter contents:
importMap.server.dev.json
{ "imports": { "graphql-react/": "https://unpkg.com/graphql-react@17.0.0/", "media_types/": "https://deno.land/x/media_types@v2.12.2/", "react": "https://esm.sh/react@17.0.2?dev", "react-dom/server": "https://esm.sh/react-dom@17.0.2/server?dev", "react-waterfall-render/": "https://unpkg.com/react-waterfall-render@4.0.0/", "ruck/": "https://deno.land/x/ruck@v1.1.0/", "std/": "https://deno.land/std@0.129.0/" } }
importMap.server.json
{ "imports": { "graphql-react/": "https://unpkg.com/graphql-react@17.0.0/", "media_types/": "https://deno.land/x/media_types@v2.12.2/", "react": "https://esm.sh/react@17.0.2", "react-dom/server": "https://esm.sh/react-dom@17.0.2/server", "react-waterfall-render/": "https://unpkg.com/react-waterfall-render@4.0.0/", "ruck/": "https://deno.land/x/ruck@v1.1.0/", "std/": "https://deno.land/std@0.129.0/" } }
importMap.client.dev.json
{ "imports": { "graphql-react/": "https://unpkg.com/graphql-react@17.0.0/", "react": "https://cdn.esm.sh/v67/react@17.0.2/es2021/react.development.js", "react-dom": "https://cdn.esm.sh/v67/react-dom@17.0.2/es2021/react-dom.development.js", "react-waterfall-render/": "https://unpkg.com/react-waterfall-render@4.0.0/", "ruck/": "https://deno.land/x/ruck@v1.1.0/" } }
importMap.client.json
{ "imports": { "graphql-react/": "https://unpkg.com/graphql-react@17.0.0/", "react": "https://cdn.esm.sh/v67/react@17.0.2/es2021/react.js", "react-dom": "https://cdn.esm.sh/v67/react-dom@17.0.2/es2021/react-dom.js", "react-waterfall-render/": "https://unpkg.com/react-waterfall-render@4.0.0/", "ruck/": "https://deno.land/x/ruck@v1.1.0/" } }
A DRY approach is to Git ignore the import map files and generate them with a script thatās a single source of truth.
A module that imports and uses Ruckās
serve
function to start the Ruck app server, typically calledscripts/serve.mjs
. Hereās an example:// @ts-check import serve from "ruck/serve.mjs"; serve({ clientImportMap: new URL( Deno.env.get("RUCK_DEV") === "true" ? "../importMap.client.dev.json" : "../importMap.client.json", import.meta.url, ), port: Number(Deno.env.get("RUCK_PORT")), }); console.info( `Ruck app HTTP server listening on http://localhost:${ Deno.env.get("RUCK_PORT") }`, );
The Deno CLI is used to run this script; Ruck doesnāt have a CLI.
You may choose to create a
scripts/serve.sh
shell script that serves the Ruck app:#!/bin/sh # Serves the Ruck app. # Asserts an environment variable is set. # Argument 1: Name. # Argument 2: Value. assertEnvVar() { if [ -z "$2" ] then echo "Missing environment variable \`$1\`." >&2 exit 1 fi } # Assert environment variables are set. assertEnvVar RUCK_DEV $RUCK_DEV assertEnvVar RUCK_PORT $RUCK_PORT # Serve the Ruck app. if [ "$RUCK_DEV" = "true" ] then deno run \ --allow-env \ --allow-net \ --allow-read \ --import-map=importMap.server.dev.json \ --watch=. \ scripts/serve.mjs else deno run \ --allow-env \ --allow-net \ --allow-read \ --import-map=importMap.server.json \ scripts/serve.mjs fi
First, ensure itās executable:
chmod +x ./scripts/serve.sh
Then, run it like this:
RUCK_DEV="true" RUCK_PORT="3000" ./scripts/serve.sh
You may choose to store environment variables in a Git ignored
scripts/.env.sh
file:export RUCK_DEV="true" export RUCK_PORT="3000"
Then, you could create a
scripts/dev.sh
shell script (also ensure itās executable):#!/bin/sh # Loads the environment variables and serves the Ruck app. # Load the environment variables. . scripts/.env.sh && # Serve the Ruck app. ./scripts/serve.sh
This way you only need to run this when developing your Ruck app:
./scripts/dev.sh
There isnāt a universally ācorrectā way to use environment variables or start serving the Ruck app; create an optimal workflow for your particular development and production environments.
A public directory containing files that Ruck serves directly to browsers, by default called
public
. For example,public/favicon.ico
could be accessed in a browser at the URL path/favicon.ico
.A
router.mjs
module in the public directory that default exports a function that Ruck calls on both the server and client with details such as the route URL to determine what the route content should be. It should have this JSDoc type:/** @type {import("ruck/serve.mjs").Router} */
Ruck provides an (optional) declarative system for automatic loading and unloading of component CSS file dependencies served by Ruck via the public directory or CDN. Ruckās
routeDetailsForContentWithCss
function can be imported and used to create route details for content with CSS file dependencies.Here is an example for a website that has a home page, a
/blog
page that lists blog posts, and a/blog/post-id-slug-here
page for individual blog posts:// @ts-check import { createElement as h } from "react"; import routeDetailsForContentWithCss from "ruck/routeDetailsForContentWithCss.mjs"; // The component used to display a route loading error (e.g. due to an // internet dropout) should be imported up front instead of dynamically // importing it when needed, as it would likely also fail to load. import PageError, { // A `Set` instance containing CSS URLs. css as cssPageError, } from "./components/PageError.mjs"; /** * Gets the Ruck app route details for a URL. * @type {import("ruck/serve.mjs").Router} */ export default function router(url, headManager, isInitialRoute) { if (url.pathname === "/") { return routeDetailsForContentWithCss( // Dynamically import route components so they only load when needed. import("./components/PageHome.mjs").then( ({ default: PageHome, css }) => ({ content: h(PageHome), css, }), // Itās important to handle dynamic import loading errors. catchImportContentWithCss, ), headManager, isInitialRoute, ); } if (url.pathname === "/blog") { return routeDetailsForContentWithCss( import("./components/PageBlog.mjs").then( ({ default: PageBlog, css }) => ({ content: h(PageBlog), css, }), catchImportContentWithCss, ), headManager, isInitialRoute, ); } // For routes with URL slugs, use RegEx that only matches valid slugs, // instead of simply extracting the whole slug. This way an invalid URL slug // naturally results in an immediate 404 error and avoids loading the route // component or loading data with the invalid slug. const matchPagePost = url.pathname.match(/^\/blog\/(?<postId>[\w-]+)$/u); if (matchPagePost?.groups) { const { postId } = matchPagePost.groups; return routeDetailsForContentWithCss( import("./components/PagePost.mjs").then( ({ default: PagePost, css }) => ({ content: h(PagePost, { postId }), css, }), ), headManager, isInitialRoute, ); } // Fallback to a 404 error page. return routeDetailsForContentWithCss( // If you have a component specifically for a 404 error page, it would be // ok to dynamically import it here. In this particular example the // component was already imported for the loading error page. { content: h(PageError, { status: 404, title: "Error 404", description: "Something is missing.", }), css: cssPageError, }, headManager, isInitialRoute, ); } /** * Catches a dynamic import error for route content with CSS. * @param {Error} cause Import error. * @returns {import("ruck/routeDetailsForContentWithCss.mjs").RouteContentWithCss} */ function catchImportContentWithCss(cause) { console.error(new Error("Import rejection for route with CSS.", { cause })); return { content: h(PageError, { status: 500, title: "Error loading", description: "Unable to load.", }), css: cssPageError, }; }
For the previous example, hereās the
public/components/PageError.mjs
module:// @ts-check import { createElement as h, useContext } from "react"; import TransferContext from "ruck/TransferContext.mjs"; import Heading, { css as cssHeading } from "./Heading.mjs"; import Para, { css as cssPara } from "./Para.mjs"; // Export CSS URLs for the component and its dependencies. export const css = new Set([ ...cssHeading, ...cssPara, "/components/PageError.css", ]); /** * React component for an error page. * @param {object} props Props. * @param {number} props.status HTTP status code. * @param {number} props.title Error title. * @param {string} props.description Error description. */ export default function PageError({ status, title, description }) { // Ruckās transfer (request/response) context; only populated on the server. const ruckTransfer = useContext(TransferContext); // If server side rendering, modify the HTTP status code for the Ruck app // page response. if (ruckTransfer) ruckTransfer.responseInit.status = status; return h( "section", { className: "PageError__section" }, h(Heading, null, title), h(Para, null, description), ); }
A
components/App.mjs
module in the public directory that default exports a React component that renders the entire app. It should have this JSDoc type:/** @type {import("ruck/serve.mjs").AppComponent} */
It typically imports and uses several React hooks from Ruck:
useCss
to declare CSS files that apply to the entire app.useHead
to establish head tags that apply to the entire app such asmeta[name="viewport"]
andlink[rel="manifest"]
.useRoute
to get the current route content, and render it in a persistent layout containing global content such as a header and footer.
Hereās an example
public/components/App.mjs
module for a website with home and blog pages:// @ts-check import { createElement as h, Fragment } from "react"; import useCss from "ruck/useCss.mjs"; import useHead from "ruck/useHead.mjs"; import useRoute from "ruck/useRoute.mjs"; import NavLink, { css as cssNavLink } from "./NavLink.mjs"; const css = new Set([ ...cssNavLink, "/components/App.css", ]); // React fragment containing globally applicable head tags. Itās defined // outside the component so it has a stable identity for React hooks. const headMetaFragment = h( Fragment, null, h("meta", { name: "viewport", content: "width=device-width, initial-scale=1", }), h("meta", { name: "theme-color", content: "white" }), h("link", { rel: "icon", href: "/favicon.ico" }), h("link", { rel: "icon", type: "image/svg+xml", sizes: "any", href: "/favicon.svg", }), h("link", { rel: "apple-touch-icon", href: "/apple-touch-icon.png" }), h("link", { rel: "manifest", href: "/manifest.webmanifest" }), ); /** * React component for the Ruck app. * @type {import("ruck/serve.mjs").AppComponent} */ export default function App() { useHead( // Head tag fragments render in the document head in key order. A good // convention is to use group and subgroup numbers, followed buy a // descriptive name. "1-1-meta", headMetaFragment, ); // This loop doesnāt break React hook rules as the list never changes. for (const href of css) useCss(href); return h( Fragment, null, // Global navā¦ h( "nav", { className: "App__nav" }, h(NavLink, { href: "/" }, "Home"), h(NavLink, { href: "/blog" }, "Blog"), ), // Route contentā¦ useRoute().content, // Global footerā¦ h("footer", { className: "App__footer" }, "Global footer content."), ); }
Ruck app route navigation links make use of these React hooks from Ruck:
useRoute
to get the current route URL path for comparison with the linkās URL path to determine active state.useOnClickRouteLink
to replace the default browser navigation that happens when a link is clicked with a Ruck client side route navigation.
For the previous example, hereās the
public/components/NavLink.mjs
module:// @ts-check import { createElement as h } from "react"; import useOnClickRouteLink from "ruck/useOnClickRouteLink.mjs"; import useRoute from "ruck/useRoute.mjs"; export const css = new Set([ "/components/NavLink.css", ]); /** * React component for a navigation link. * @param {object} props Props. * @param {string} props.href Link URL. * @param {import("react").ReactNode} [props.children] Children. */ export default function NavLink({ href, children }) { const route = useRoute(); const onClick = useOnClickRouteLink(); let className = "NavLink__a"; if (href === route.url.pathname) className += " NavLink__a--active"; return h("a", { className, href, onClick }, children); }
Examples
Requirements
- Deno CLI v1.13.2+.
Contributing
Scripts
These CLI scripts are used for development and GitHub Actions CI checks.
Install
To install development dependencies (primarily Puppeteer):
./scripts/install.sh
Test
Beforehand, run the install script. To run the tests:
./scripts/test.sh
Serve
To serve the Ruck project files for testing in other local projects (argument 1 is the localhost port for the HTTP server to listen on):
./scripts/serve.sh 3001
Format
To format the project:
deno fmt
Lint
To lint the project:
deno lint