跳到主要内容
EnglishEnglish查看本页的英文版本。
浏览文档

教程:第一个应用

从空目录开始做一个完整的小应用:创建项目、加一个页面、加一个 island、加一个表单 action,最后构建并起服务——每一步都给出命令和预期结果。

适用于 v1.0.0-alpha.16 · 更新于

1.0.0-alpha.16 是 Element 与 Router 的当前基线,已通过 @alpha dist-tag 发布到 npm。 下文讲的是基线创作面,也就是本指南通篇记录的那一套。

开始之前

需要 Node.js 24.2+ 与一个终端;任何包管理器都可以(npm、pnpm、yarn、bun——本指南统一写成 npm run …)。唯一一条 bootstrap 命令是一次普通的 Node 调用(ADR-0161)——不涉及第二个运行时,之后的每一步都是普通的 Node 工具链。

本教程用五步做出一个小应用,每一步都以「看得见的结果」收尾:

  1. 创建项目——把 starter 落到磁盘,并在 dev 下跑起来。
  2. 加一个页面——一个新 URL,返回 HTML。
  3. 加一个 island——一个会在浏览器里「醒来」的组件。
  4. 加一个表单 action——一个 POST:要么校验失败,要么保存并重定向。
  5. 构建并起服务——产出可以部署的 dist/。

本页的 TypeScript 与 TSX 代码块不是示意片段:www#check:content 会用真实编译器、对着框架源码把它们编译一遍——本地 vp run site:verify 与发布门禁(release:check 的 gate:release)各跑一次;PR CI 不跑这一步,因此过期代码块由发布列车发现,而不是每次提交。

第 1 步:创建项目

npm create @openelement my-app
cd my-app
npm run dev

这条命令跑在普通 Node 工具链上:从 npm 拉取已发布的 @openelement/create 包——无 tag 的安装解析 latest,即当前 1.0 线——并以该版本为下限,把 @openelement/* 的 caret 范围写进项目;依赖也由它自己安装,所以没有单独的 install 命令。

create CLI 每个文件打印一行 created <path>,随后是交接框:写明生成器版本与下一步(框里两条命令都按它检测到的包管理器拼写;加 --no-install 时先打印安装命令——同样按检测到的包管理器,PATH 上一个都没有时退回 npm install——再打印 dev):

openElement project created at ./my-app/ (template: showcase)
  initialized git repository (with .gitignore)

openElement project ready
(@openelement/create <version>)

cd my-app
npm run dev      # start the dev server

Docs: https://openelement.org

npm run dev 启动 Vite dev server,并打印要打开的地址:

  VITE v8.1.6  ready in 412 ms

  ➜  Local:   http://localhost:5173/

这个页面就是 starter 的首页路由。它的目录结构就是整个架构:

my-app/
  package.json      dependencies + scripts: dev, build, start, test, typecheck
  openelement.config.ts  framework options (tokens, head, shell conventions)
  vite.config.ts    Vite configuration; the plugin call takes no arguments
  app/routes/       one file per URL
  app/components/   page-scope components and their style sheets
  app/islands/      modules that opt into client delivery
  public/           static assets, copied into dist/ as-is

npm run typecheck 会类型检查 starter 的 app/ 目录以及 vite.config.ts 与 openelement.config.ts;新增的路由会被自动纳入。

第 2 步:加第一个页面

URL 就是文件:app/routes/hello.tsx 对应 /hello。标记是静态文本的页面只需要这一个文件——路由模块导出一个组件,再用 definePage 把它包起来。

// app/routes/hello.tsx
import { definePage } from '@openelement/router';

export function HelloPage() {
  return (
    <main>
      <h1>Hello from a page</h1>
      <p>This markup is server-rendered HTML, with no client JavaScript.</p>
    </main>
  );
}

export default definePage(HelloPage, {
  head: {
    title: 'Hello — my-app',
    description: 'The tutorial page.',
  },
});

关于这个模块,现在就该知道两件事:

  • 它是一个服务端函数页:编译器把导出的函数降级成一个生成式 HTML 构造器,所以这个页面在构造上就在服务端渲染,页面函数本身不进入客户端模块。
  • definePage 只接受 route、head、renderIntent、props 和 error。没有 render() 字段,也没有 route.path——URL 由文件名决定。

预期结果:dev server 不需要重启就会接管新文件。打开 http://localhost:5173/hello,或者直接看响应:

curl -s http://localhost:5173/hello | grep -o 'Hello from a page'
Hello from a page

标题本来就在服务端发出的 HTML 里,不是脚本注入的。这个页面加载的客户端模块只有 starter 自带的 app-layout;这条路由本身没有引入任何 island。

第 3 步:加第一个 island

island 就是 app/islands/ 下的一个模块。这个目录本身就是注册面:没有任何地方 import 它,构建会扫描该目录,并从文件名推导标签名(hello-counter.tsx → <hello-counter>)。

app/islands/hello-counter.tsx:

import { signal } from '@openelement/element';
import { defineIslandConfig } from '@openelement/router';

export const openElement = defineIslandConfig({
  tag: 'hello-counter',
  // shadow root 正是让计数器的标记成为 DSD 模板、由浏览器在任何脚本
  // 运行之前解析的那个选择。
  root: 'shadow',
  hydrate: 'idle',
  ssr: true,
  dsd: true,
});

export default function HelloCounter() {
  // 计数是一个信号,所以文本与两个按钮读的是同一个来源,
  // 也只有读取它的那些槽位会刷新。
  const count = signal(0);

  return (
    <div class='counter-row'>
      <button type='button' onClick={() => { count.value = count.value - 1; }}>-</button>
      <span id='count'>{count.value}</span>
      <button type='button' onClick={() => { count.value = count.value + 1; }}>+</button>
    </div>
  );
}

接着让刚才那个页面承载它。app/routes/hello.tsx 变成:

import { definePage } from '@openelement/router';
// 副作用导入正是构建得知这个页面能到达该 island 的方式。
import '../islands/hello-counter.tsx';

export function HelloPage() {
  return (
    <main>
      <h1>Hello from a page</h1>
      <p>This markup is server-rendered HTML, with no client JavaScript.</p>
      <section class='demo'>
        <p>The server sent this counter's markup; the browser upgrades it on idle.</p>
        <hello-counter></hello-counter>
      </section>
    </main>
  );
}

export default definePage(HelloPage, { head: { title: 'Hello — my-app' } });

预期结果——刷新 http://localhost:5173/hello:

  • 在任何 JavaScript 执行之前,响应里就已经有计数器标记,里面的数字是 0:island 通过同一个编译组件在服务端完成了渲染。
  • 点 + 和 -,数字会变。hydrate: 'idle' 让浏览器在页面稳定后去取该 island 的 chunk、upgrade 元素,并绑定编译组件声明过的那些事件处理。
  • 没有任何路由引用的 island 永远不会被投递——构建从你的路由源码推导可达标签,所以只往 app/islands/ 里放一个模块,不会给任何页面增加 JavaScript。

第 4 步:加一个表单 action

路由模块还可以导出 action。表单本身是纯 HTML,所以 notes 页面不需要任何客户端行为,仍然是一个服务端函数页。

// app/routes/notes.tsx
import { definePage, fail, redirect, type OpenElementActionFailure } from '@openelement/router';

interface NotesActionData {
  error?: string;
  note?: string;
}

export function action(ctx: { formData: FormData }): OpenElementActionFailure<NotesActionData> {
  const note = String(ctx.formData.get('note') ?? '').trim();
  if (!note) {
    return fail(422, { error: 'a note is required', note });
  }
  throw redirect(`/notes?saved=${encodeURIComponent(note)}`);
}

export function NotesPage(props: { note: string; error: string; saved: string }) {
  return (
    <main>
      <h1>Notes</h1>
      <form method='post' data-open-enhance>
        <input name='note' type='text' value={props.note} placeholder='Write a note' />
        <button type='submit'>Save</button>
      </form>
      <p id='error'>{props.error}</p>
      <p id='saved'>{props.saved}</p>
    </main>
  );
}

export default definePage(NotesPage, {
  renderIntent: { mode: 'dynamic' },
  head: { title: 'Notes — my-app' },
  props({ request, actionData }) {
    const saved = request ? new URL(request.url).searchParams.get('saved') : undefined;
    const result = actionData as NotesActionData | undefined;
    return {
      note: result?.note ?? '',
      error: result?.error ?? '',
      saved: saved ?? '',
    };
  },
});

各部分的作用:

  • 表单是纯 HTML,没有 JavaScript 也能用。那种提交会在服务端执行 action;fail(422, …) 用报错文案和用户刚输入的值重新渲染同一个页面。
  • redirect() 用一个 303 指向一个 GET 地址——即 post/redirect/get,因此刷新结果页不会重复提交。
  • 这里的 renderIntent: { mode: 'dynamic' } 是有意的:GET 要从请求里读 ?saved=,必须按请求渲染。GET 不需要请求的页面可以保持 'static' 并同样导出 action,此时只有 POST 走请求时路径。
  • props 是请求作用域与编译标记之间唯一的接缝。它返回一个对象,每个键设置页面组件上同名的声明属性。

预期结果:data-open-enhance 用 fetch 提交表单,并把返回的文档 morph 到位,页面不整页刷新。想看协议本身,可以直接向 action 发请求:

curl -i -X POST -H 'x-openelement-action: true' --data 'note=' http://localhost:5173/notes
HTTP/1.1 422 Unprocessable Entity
content-type: application/problem+json; charset=utf-8
curl -i -X POST -H 'x-openelement-action: true' --data 'note=hello' http://localhost:5173/notes
HTTP/1.1 303 See Other
location: /notes?saved=hello

不带 x-openelement-action 头时,同一个 POST 就是普通的浏览器表单提交,返回 HTML 而不是 JSON。当一个表单需要多个提交按钮时,路由还可以导出 actions,用 formaction='?/name' 分发。

第 5 步:构建并起服务

npm run build

构建会预渲染所有静态路由、为每个可达 island 打一个 chunk,并且——因为 /notes 是请求时的——同时写出服务端入口。预期输出(已截取:starter 自带的 island 也在同一张表里,逐页清单省略):

== openElement Build Manifest - Phase 3 @ 12:04:31 ==

  Client Islands:
  File                         Size
  --------------------------   --------
  ...
  hello-counter.js             …
  --------------------------   --------
  TOTAL JS                     …

  ...
  All artifacts within budget limits
ls dist

本教程的作品对应的产物:

index.html          预渲染的 /
hello/index.html    预渲染的 /hello
client/islands/     每个可达 island 一个 chunk
island-manifests/   page-<hash>.json——记录每个页面加载哪些 island
server/index.js     请求时处理器:回答 POST /notes,并为未匹配路径
                    渲染带样式的 404

起服务:

npm start
[openElement start] request-time server entry loaded (dynamic routes enabled)
[openElement start] http://localhost:4173

端口取自 OPEN_ELEMENT_PORT,其次是 PORT,默认 4173。要验证的是产物,而不是日志:

curl -i http://localhost:4173/hello | head -1
HTTP/1.1 200 OK

/hello 是磁盘上的文件;/notes 走到了服务端入口——未匹配路径的带样式 404 也一样。构建产物没有请求时路由的项目可以用 openelement start --mode=preview 只起静态产物,而这个项目有请求时路由,所以要用 npm start 起。

到这里你有了一个项目、一个页面、一个 island、一个表单 action,以及一份可以部署的构建产物。

下一步

  • 路由与数据——loader、具名 action,以及两条 loader/action 链路。
  • Islands 与 SSR——投递策略,以及真正发到浏览器的东西。
  • 部署——完整的产物契约与 Nitro preset。

另见

  • 核心概念——sidecar 及其属性背后的组件模型。
  • 样式——页面样式放在哪里,以及什么能穿过 shadow 边界。
  • 测试——面对构建产物值得跑的检查。