Web: TypeScript and React Router
These are the steps to set up and run a simple TypeScript Web app that calls into a shared core.
This walk-through assumes you have already set up the shared library and codegen as described in Getting started.
There are many frameworks available for writing Web applications with JavaScript/TypeScript. We've chosen React with React Router for this walk-through. However, a similar setup would work for other frameworks.
Create a React Router App
For this walk-through, we'll use the pnpm package manager
for no reason other than we like it the most! You can use npm exactly the same
way, though.
Let's create a simple React Router app for TypeScript with pnpm. You can give
it a name and then probably accept the defaults.
pnpm create react-router@latest
Compile our Rust shared library
When we build our app, we also want to compile the Rust core to WebAssembly so that it can be referenced from our code.
To do this, we'll use BoltFFI, which you can install like this:
cargo install boltffi_cli --version '=0.32.1' --locked
brew install binaryen # provides wasm-opt
The crate is boltffi_cli; it installs the boltffi binary used below.
Binaryen must be version 123 or newer, because BoltFFI passes --enable-bulk-memory-opt
to wasm-opt, which older releases don't understand. Check with
wasm-opt --version; distribution packages are often well behind, so prefer a
release from GitHub if your
package manager ships something older.
Add the shared Wasm package and the BoltFFI runtime to your
web-react-router project:
cd web-react-router
pnpm add shared@link:./generated/pkg @boltffi/runtime@0.32.1
The Wasm package does not exist yet. A link: dependency is a symbolic link, so
pnpm can add it before BoltFFI writes the package. pnpm does not install the
dependencies of a linked package, so the app lists @boltffi/runtime itself.
The app also needs @types/node in its devDependencies (the React Router
template adds it).
Now that we have boltffi installed, we can build our shared library to
WebAssembly for the browser. BoltFFI type-checks the TypeScript bindings that
it generates against @boltffi/runtime and @types/node in the node_modules
of web-react-router. Thus you must install the dependencies before you run it:
(cd ../shared && boltffi pack wasm)
You might want to add a wasm:build script to your package.json file, and
call it when you build your React Router project.
{
"scripts": {
"build": "pnpm run wasm:build && react-router build",
"dev": "pnpm run wasm:build && react-router dev",
"wasm:build": "cd ../shared && boltffi pack wasm"
}
}
We want Vite to bundle our shared Wasm package for the browser, so we
register the wasm and React Router plugins in vite.config.ts:
import { reactRouter } from "@react-router/dev/vite";
import wasm from "vite-plugin-wasm";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [wasm(), reactRouter()],
ssr: {
// The server loads `shared` from node_modules, because its Node.js glue
// reads the .wasm file next to it at run time.
external: ["shared"],
},
});
The ssr setting controls the server build. The server loads shared from
node_modules, because its Node.js code reads the .wasm file next to it at
run time.
Add the Shared Types
To generate the shared types for TypeScript, run the codegen binary, telling
it which language to emit and where to put the output:
cargo run --package shared --bin codegen --features codegen,facet_typegen -- \
--language typescript --output-dir generated/types
You can check that they have been generated correctly:
ls --tree generated/types
generated/types
├── app.ts # your app's Event / Effect / ViewModel types
├── app.js
├── app.d.ts
├── bincode
│ ├── bincodeDeserializer.ts
│ ├── bincodeSerializer.ts
│ └── index.ts
├── serde
│ ├── binaryDeserializer.ts
│ ├── binarySerializer.ts
│ ├── deserializer.ts
│ ├── serializer.ts
│ ├── types.ts
│ └── index.ts
├── package.json
└── tsconfig.json
You can see that it also generates an npm package that we can add directly to
our project. The generated package depends on the Wasm package, so add it as a
link: dependency too:
pnpm add shared_types@link:./generated/types
Load the Wasm binary when our React Router app starts
The app/entry.client.tsx file is where we load our Wasm binary. We import the
shared package and wait for its initialized promise to resolve before
hydrating the app, so the WASM module is ready before any event reaches the
core.
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
import * as sharedWasm from "shared";
const wasmInitialized = (
sharedWasm as unknown as { initialized: Promise<void> }
).initialized;
wasmInitialized
.then(() => {
startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<HydratedRouter />
</StrictMode>,
);
});
})
.catch(console.error);
Create some UI
We will use the simple counter example, which has a shared library and generated TypeScript types that will work with the following example code.
Simple counter example
A simple app that increments, decrements and resets a counter.
Write the effect handler
The generated types include a Core class that drives the loop between the
shell and the Rust core: it serializes the events we send, passes them to the
core, deserializes the requests that come back and dispatches each one to an
EffectHandler that we write. Because the codegen binary was told where
boltffi pack wasm puts the bindings (with .boltffi(..), see
Type generation), it also
generates the FfiBridge that carries the bytes to and from CoreFfi, so
there is no hand-written wrapper.
Edit app/core.ts to look like the following. The generated EffectHandler
interface has one method per operation the app declares. The counter's only
effect is Render, which the generated Core handles itself (it reads the
new view model and passes it to the onView callback), so CounterHandler
is empty.
Core.create is an async factory rather than a constructor, because it
waits for the Wasm module's initialized promise before it builds the bridge.
import type { EffectHandler, ViewModel } from "shared_types/app";
import { Core } from "shared_types/app";
/**
* The shell's side of the effect protocol.
*
* `CounterHandler` implements the generated `EffectHandler`, which has one
* method per operation the app declares. The counter's only effect is
* `Render`, and the generated `Core` handles that itself (reading the new
* view model and passing it to the `onView` callback), so there is nothing
* left for the handler to do.
*/
export class CounterHandler implements EffectHandler {}
/**
* Everything the shell has to write to run a Crux core: an `EffectHandler`
* for the app's operations and a callback for the view model. `Core.create`
* waits for the wasm module, builds the generated `FfiBridge` over it, and
* owns the loop between them.
*/
export function createCore(onView: (view: ViewModel) => void): Promise<Core> {
return Core.create(new CounterHandler(), onView);
}
CounterHandler is where you would handle any other effects that your core
might ask for. For example, if your core needs to make an HTTP request, the
generated EffectHandler gains a method for that operation, which returns the
response.
To see an example of this, take a look at the
weather example
in the Crux repository.
Create a component to render the UI
Edit app/routes/_index.tsx to look like the following. When the component
mounts, we create the core, passing the setView state setter as the onView
callback, so every Render from the core updates the view. The onView
callback is only called on a render, so we also set the view once from
core.view when the core has been created. The buttons send events to the
core with update.
import { useEffect, useRef, useState } from "react";
import type { Core } from "shared_types/app";
import {
ViewModel,
eventReset,
eventIncrement,
eventDecrement,
} from "shared_types/app";
import { createCore } from "../core";
export const meta = () => {
return [
{ title: "Crux Counter — React Router" },
{ name: "description", content: "Crux Counter with React Router" },
];
};
export default function Index() {
const [view, setView] = useState(new ViewModel(""));
const core = useRef<Core | null>(null);
const initialized = useRef(false);
useEffect(() => {
if (initialized.current) return;
initialized.current = true;
void createCore(setView).then((created) => {
core.current = created;
// `onView` is only called on a render, so show the initial view now.
setView(created.view);
});
}, []);
return (
<main>
<section className="box container has-text-centered m-5">
<p className="is-size-5">{view.count}</p>
<div className="buttons section is-centered">
<button
className="button is-primary is-danger"
onClick={() => core.current?.update(eventReset())}
>
{"Reset"}
</button>
<button
className="button is-primary is-success"
onClick={() => core.current?.update(eventIncrement())}
>
{"Increment"}
</button>
<button
className="button is-primary is-warning"
onClick={() => core.current?.update(eventDecrement())}
>
{"Decrement"}
</button>
</div>
</section>
</main>
);
}
Now all we need is some CSS.
To add a CSS stylesheet, we can add it to the Links export in the
app/root.tsx file.
export const links: LinksFunction = () => [
{
rel: "stylesheet",
href: "https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css",
},
];
Build and serve our app
We can build our app, and serve it for the browser, in one simple step.
pnpm dev
