# LynxJS 在浏览器中运行移动端界面 —— 可执行搭建手册 > 目标:用 ReactLynx + Rspeedy 写一份移动端界面代码,构建出 Web 产物,在浏览器里通过 `` 渲染出来。 > 调研时间:2026 年(版本号取自 npm registry 的 `dist-tags.latest`)。所有关键结论均附来源 URL。 --- ## 0. 先看结论:最短可行路径(TL;DR) ```bash # 1) 脚手架(注意:是 create rspeedy,不是 create lynx) npm create rspeedy@latest my-lynx-app # 选择 React + TypeScript + Rspeedy cd my-lynx-app npm install # 2) 让 Rspeedy 同时产出 web 产物:编辑 lynx.config.ts 加 environments # environments: { lynx: {}, web: {} } # 3) 因为产物是 .web.bundle,需要自己写一个 index.html 去挂 # 最省事的做法:把 index.html 放进项目根的 public/ 目录(见 §3.4) # 4) 开发 npm run dev # Rspeedy dev server,默认 http://localhost:3000 # 5) 打开浏览器 # http://localhost:3000/index.html ``` **一句话原理**:Rspeedy 用 `environments` 区分平台,产物文件名模板是 `[name].[platform].bundle`,所以 `web` 环境产出 `dist/main.web.bundle`;浏览器侧用 `@lynx-js/web-core` 注册一个 `` 自定义元素,把 `url` 指向这个 `.web.bundle`,Lynx 就在浏览器里跑起来了(自定义元素映射到真实 DOM,用浏览器的 CSS/布局引擎渲染)。 **必须知道的三个反直觉点**: 1. `npm create lynx@latest` 是**错的**(见 §1.3)。 2. Rspeedy **不会**给你生成 HTML 页面,`` 那层 HTML 要你自己写(见 §4)。 3. 入口是 `root.render()` 而不是 `createRoot(...).render(...)`。 --- ## 1. 当前版本号(2026 年,npm registry `dist-tags.latest`) ### 1.1 核心包版本表 | 包名 | latest 版本 | 说明 | 来源 | | --- | --- | --- | --- | | `@lynx-js/react` | **0.126.2** | ReactLynx 框架本体(基于 Preact) | https://registry.npmjs.org/@lynx-js%2Freact/latest | | `@lynx-js/rspeedy` | **0.18.0** | 构建工具(Rspack 驱动) | https://registry.npmjs.org/@lynx-js%2Frspeedy/latest | | `@lynx-js/react-rsbuild-plugin` | **0.20.3** | ReactLynx 的 Rsbuild 插件(`pluginReactLynx`) | https://registry.npmjs.org/@lynx-js%2Freact-rsbuild-plugin/latest | | `@lynx-js/web-core` | **0.26.2** | **Web 端运行时,提供 ``** | https://registry.npmjs.org/@lynx-js%2Fweb-core/latest | | `@lynx-js/web-elements` | **0.12.12** | Web 自定义元素实现(web-core 的依赖) | https://registry.npmjs.org/@lynx-js%2Fweb-elements/latest | | `@lynx-js/lynx-ui` | **3.139.0** | 官方 headless 组件库 | https://registry.npmjs.org/@lynx-js%2Flynx-ui/latest | | `@lynx-js/types` | **4.3.0** | Lynx API / 元件类型定义 | https://registry.npmjs.org/@lynx-js%2Ftypes/latest | | `@lynx-js/qrcode-rsbuild-plugin` | **0.7.3** | 终端二维码插件(`pluginQRCode`) | https://registry.npmjs.org/@lynx-js%2Fqrcode-rsbuild-plugin/latest | | `@lynx-js/create-lynx` | **0.2.1** | **真正的脚手架本体** | https://registry.npmjs.org/@lynx-js%2Fcreate-lynx/latest | | `create-rspeedy` | **0.18.0** | 脚手架入口(现已转发到 `@lynx-js/create-lynx`) | https://registry.npmjs.org/create-rspeedy/latest | | `@lynx-js/web-platform-rsbuild-plugin` | **0.1.2** | Web 侧构建性能优化插件(可选) | https://registry.npmjs.org/@lynx-js%2Fweb-platform-rsbuild-plugin/latest | ### 1.2 关键兼容性约束(从 registry 元数据里读出来的) - `@lynx-js/rspeedy@0.18.0` 的 `engines.node` = `^20.19.0 || >=22.12.0`。**Node 20.19 以下直接不支持**。 - `@lynx-js/react-rsbuild-plugin@0.20.3` 的 peerDependencies: - `@lynx-js/react`: `^0.124.0 || ^0.125.0 || ^0.126.0` - `@lynx-js/rspeedy`: `^0.17.0 || ^0.18.0` - `@rsbuild/core`: `^2.0.0` - 也就是说 `@lynx-js/react@0.126.2` + `@lynx-js/rspeedy@0.18.0` + 插件 `0.20.3` 是当前官方自测的组合。 - `@lynx-js/rspeedy@0.18.0` 依赖 `@rsbuild/core@2.2.9`(即 Rspeedy 0.18 建立在 Rsbuild 2.x / Rspack 2.x 之上)。 - `@lynx-js/web-core@0.26.2` 依赖 `@lynx-js/web-elements@0.12.12`、`@lynx-js/web-worker-rpc@0.26.2`;`browserslist.production` = `Chrome >= 92, Safari >= 16.4`。 - `@lynx-js/lynx-ui@3.139.0` 的 peerDependencies:`@lynx-js/react >=0.100.0`、`@lynx-js/types *`、`@types/react ^18`。 ### 1.3 ⚠️ `create lynx` 是坑 - npm 上确实存在 `create-lynx@1.0.0`(https://www.npmjs.com/package/create-lynx),但它**不是字节的包**:作者 `loisz`,2025-01-17 发布,`unpackedSize` 仅 **225 字节**,只有一个 `index.js`,`license: ISC`,没有任何 Lynx 官方仓库关联。**不要用**。 - 官方脚手架是 **`@lynx-js/create-lynx`**(Apache-2.0,仓库 `github.com/lynx-family/lynx-stack` 的 `packages/rspeedy/create-lynx`)。 - `create-rspeedy@0.18.0` 的 package.json 描述写得很直白:`"description": "Deprecated: use @lynx-js/create-lynx instead"`,且 `"dependencies": { "@lynx-js/create-lynx": "0.2.1" }` —— 所以 `npm create rspeedy@latest` 只是官方留的兼容入口。 - 官方快速开始页明确推荐:**推荐通过 `create-rspeedy` 来快速创建一个 Lynx 项目**,命令是 `npm create rspeedy@latest`。 来源:https://lynxjs.org/zh/guide/start/quick-start.md **两者都可用**: ```bash npm create rspeedy@latest my-lynx-app # 官方文档写法(推荐,等价转发) # 或 npm create @lynx-js/lynx@latest my-lynx-app # 直接调用真正的脚手架 ``` ---## 2. 脚手架生成的目录结构与关键文件内容 ## 2. 脚手架生成的目录结构与关键文件内容 ### 2.1 交互式提问 `npm create rspeedy@latest` 会依次问:项目名 → 是否用 TypeScript → 选模板。选 **React + TypeScript + Rspeedy** 会生成 `template-rspeedy-react-ts`,这也是下面所有内容的依据。 来源:https://github.com/lynx-family/lynx-stack/tree/main/packages/rspeedy/create-lynx/template-rspeedy-react-ts ### 2.2 目录结构(以 `template-rspeedy-react-ts` 为准) ```text my-lynx-app/ ├── package.json ├── lynx.config.ts # Rspeedy 配置(注意:不是 rsbuild.config.ts) ├── tsconfig.json # 根 tsconfig,只做 references ├── tsconfig.node.json # 给 lynx.config.ts 用 ├── rstest.config.ts └── src/ ├── tsconfig.json # 源码的 tsconfig(jsx / jsxImportSource 在这里) ├── lynx-env.d.ts # Rspeedy 类型声明(等价于文档里的 rspeedy-env.d.ts) ├── index.tsx # 入口 ├── App.tsx # 示例组件 ├── App.css ├── assets/ │ ├── arrow.png │ ├── lynx-logo.png │ └── react-logo.png ├── lib/flappy.ts ├── useFlappy.ts └── __tests__/index.test.tsx ``` > 注意:Rspeedy 模板里配置文件叫 **`lynx.config.ts`**;而那个 `template-rsbuild-react-ts`(不用 Rspeedy 的变体)里叫 `rsbuild.config.ts` 并且 `dev` 脚本是 `rsbuild dev`。**我们要的是 Rspeedy 版,务必确认文件名是 `lynx.config.ts`、scripts 里是 `rspeedy dev`。** ### 2.3 `package.json` 脚手架模板里的依赖是 monorepo 的 `workspace:*`,会由 create-lynx 在生成时替换为真实版本号。写成可直接安装的形式如下: ```json { "name": "my-lynx-app", "version": "0.0.0", "type": "module", "scripts": { "build": "rspeedy build", "dev": "rspeedy dev", "preview": "rspeedy preview", "test": "rstest run" }, "dependencies": { "@lynx-js/react": "^0.126.2" }, "devDependencies": { "@lynx-js/preact-devtools": "^5.0.1-20260827072047-5f77e12", "@lynx-js/qrcode-rsbuild-plugin": "^0.7.3", "@lynx-js/react-rsbuild-plugin": "^0.20.3", "@lynx-js/rspeedy": "^0.18.0", "@lynx-js/types": "^4.3.0", "@rsbuild/plugin-type-check": "^1.6.0", "@rstest/core": "^0.12.1", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "^7.0.0", "@types/react": "^19.2.18", "jsdom": "^27.4.0", "typescript": "^6.0.3" }, "engines": { "node": "^20.19.0 || >=22.12.0" } } ``` 模板原始内容(`workspace:*` 形式): ```json { "name": "lynx-rspeedy-react-ts", "version": "0.0.0", "type": "module", "scripts": { "build": "rspeedy build", "dev": "rspeedy dev", "preview": "rspeedy preview", "test": "rstest run" }, "dependencies": { "@lynx-js/react": "workspace:*" }, "devDependencies": { "@lynx-js/preact-devtools": "workspace:*", "@lynx-js/qrcode-rsbuild-plugin": "workspace:*", "@lynx-js/react-rsbuild-plugin": "workspace:*", "@lynx-js/types": "workspace:*", "@rsbuild/plugin-type-check": "workspace:*", "@rstest/core": "workspace:*", "@testing-library/dom": "workspace:*", "@testing-library/jest-dom": "workspace:*", "@types/react": "workspace:*", "jsdom": "workspace:*", "typescript": "workspace:*" }, "engines": { "node": "^20.19.0 || >=22.12.0" } } ``` 注意 **`"type": "module"`** —— 配置文件是 ESM。 ### 2.4 `lynx.config.ts`(模板原样) ```ts import { pluginQRCode } from '@lynx-js/qrcode-rsbuild-plugin'; import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin'; import { defineConfig } from '@lynx-js/rspeedy'; export default defineConfig({ source: { entry: { main: './src/index.tsx', }, }, plugins: [ pluginQRCode({ schema(url) { // We use `?fullscreen=true` to open the page in LynxExplorer in fullscreen mode return `${url}?fullscreen=true`; }, }), pluginReactLynx(), ], }); ``` **改造为同时产出 web 产物**(这是本手册的核心改动,见 §3.3): ```ts import { pluginQRCode } from '@lynx-js/qrcode-rsbuild-plugin'; import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin'; import { defineConfig } from '@lynx-js/rspeedy'; export default defineConfig({ source: { entry: { main: './src/index.tsx', }, }, environments: { lynx: {}, web: {}, }, plugins: [ pluginQRCode({ schema(url) { return `${url}?fullscreen=true`; }, }), pluginReactLynx(), ], }); ``` > `pluginQRCode` 只对原生调试有意义(终端二维码给 LynxExplorer 扫)。纯做 Web 时留着无害,也可以删掉。 ### 2.5 `src/index.tsx`(模板原样,注意没有 createRoot) ```tsx import '@lynx-js/preact-devtools'; import '@lynx-js/react/debug'; import { root } from '@lynx-js/react'; import { App } from './App.js'; root.render(); if (import.meta.webpackHot) { import.meta.webpackHot.accept(); } ``` ### 2.6 `src/App.tsx`(模板原样) ```tsx import { useCallback, useEffect, useState } from '@lynx-js/react'; import './App.css'; import arrow from './assets/arrow.png'; import lynxLogo from './assets/lynx-logo.png'; import reactLynxLogo from './assets/react-logo.png'; export function App() { const [alterLogo, setAlterLogo] = useState(false); useEffect(() => { console.info('Hello, ReactLynx'); }, []); const onTap = useCallback(() => { "background-only"; setAlterLogo(!alterLogo); }, [alterLogo]); return ( {alterLogo ? : } React on Lynx Tap the logo and have fun! Edit{" src/App.tsx "} to see updates! ); } ``` 要读出来的三件事:**`` 是根节点**、文字全部包在 `` 里、点击用 `bindtap` 而不是 `onClick`。 ### 2.7 `tsconfig.json`(根,模板原样) ```json { "compilerOptions": { "strict": true, "isolatedModules": true, "verbatimModuleSyntax": true, "esModuleInterop": true, "skipLibCheck": true }, "references": [{ "path": "./tsconfig.node.json" }, { "path": "./src" }], "files": [] } ``` ### 2.8 `src/tsconfig.json`(**关键:jsxImportSource**) ```json { "extends": "../tsconfig.json", "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "@lynx-js/react", "lib": ["ES2023", "DOM", "DOM.Iterable"], "module": "ESNext", "moduleResolution": "Bundler", "noEmit": true, "allowJs": true, "types": ["@lynx-js/rspeedy/client"], "composite": true, "verbatimModuleSyntax": true }, "include": [".*/*.ts", "./*.tsx"] } ``` > `"jsx": "react-jsx"` + `"jsxImportSource": "@lynx-js/react"` **两个都要有**。只写 `jsx: react-jsx` 会让 TS 去解析 `react/jsx-runtime`,类型全错。 > 来源:https://lynxjs.org/zh/llms.txt(第 8 节「类型系统」) > > ⚠️ 上面 `include` 的 glob 是从模板 base64 内容转录的,可能有转义失真。实际以脚手架生成的文件为准;它写错也不影响 Rspeedy 构建(Rspeedy **默认不跑类型检查**,需要的话要另外装 `@rsbuild/plugin-type-check`)。 > 来源:https://lynxjs.org/zh/rspeedy/typescript.md > > ⚠️ `@lynx-js/types`:脚手架模板里 pin 的是 `4.1.0`,而 npm 上 latest 已是 **4.3.0**。用 `^4.3.0` 或让脚手架自己决定都可以。 ### 2.9 `tsconfig.node.json` ```json { "compilerOptions": { "allowJS": true, "composite": true, "module": "ESNext", "moduleResolution": "Bundler", "noEmit": true, "types": [], "lib": ["ES2023"] }, "include": ["./lynx.config.ts"] } ``` ### 2.10 `src/lynx-env.d.ts` ```ts /// ``` 这一行负责给 `*.png`、`*.module.css` 等资源/样式导入提供类型。 来源:https://lynxjs.org/zh/rspeedy/typescript.md 、https://lynxjs.org/zh/rspeedy/assets.md > 文档里这个文件叫 `src/rspeedy-env.d.ts`,模板里叫 `src/lynx-env.d.ts`,**文件名无所谓,内容那一行 reference 才是关键**。 --- ## 3. 在浏览器/Web 中渲染 Lynx 页面 ### 3.1 架构说明:Web 端是怎么跑的 - `@lynx-js/web-core` 在 Web 上实现了 Lynx 引擎的 native binding API:它用**浏览器的 CSS 引擎、布局引擎、渲染引擎**提供渲染管线,用浏览器的 JS 引擎跑 JS。 - UI 元件映射为一组 **Custom Elements**(`@lynx-js/web-elements` 包提供,如 `XView`/`XText`/`XImage`/`ScrollView`/`XList`…)。 - 与 Android/iOS 产物的差别在于:原生平台的产物做了 AOT 字节码优化(`encode`),因为那边没有 JIT;**Web 端的产物不做这个优化,所以是另一种格式** —— 这就是为什么需要 `.web.bundle`。 来源:https://github.com/lynx-family/lynx-stack/blob/main/packages/web-platform/readme.md ### 3.2 `` 的用法(官方 API) ```ts import '@lynx-js/web-core/client'; ``` 就这一行,**不需要再手动 import CSS,也不需要 import `@lynx-js/web-elements`**(`@lynx-js/web-core@0.20.0` 架构升级后已简化)。 `` 属性: | 属性 | 必填 | 说明 | | --- | --- | --- | | `url` | **是** | Rspeedy 产物的 URL(其它 chunk 的 url 会被编译期注入产物自动启动) | | `globalProps` | 否 | 初始化时的 GlobalProps | | `initData` | 否 | 初始化时的 InitData | | `browser-config` | 否 | 实例级动态配置 `systemInfo`,如 `pixelRatio` / `pixelWidth` / `pixelHeight` | | `transform-vw` | 否 | 开启 vw 转换,`1vw` → `calc(1 * var(--vw-unit))` | | `transform-vh` | 否 | 同上,vh | **宽高是硬性要求**:`lynx-view` 内部排版会被强制移出外部排版流,所有 `lynx-view` 都被强制应用 CSS Containment。默认**必须**给它设置宽高(可以来自 `flex-grow`,可以是百分比,但**不能靠内容撑开**)。确实需要内容决定宽度/高度时,用 `height="auto"` / `width="auto"` 启动自动宽高监听。 **已在 0.20.0 移除的属性**(别再照抄旧博客):`thread-strategy`、`customTemplateLoader`、`overrideLynxTagToHTMLTagMap`、`inject-head-links`。 来源:https://lynxjs.org/zh/api/lynx-native-api/lynx-view/lynx-view.md ### 3.3 Rspeedy 如何构建出 web 可用的 bundle 在 `lynx.config.ts` 里加 `environments`: ```ts export default defineConfig({ environments: { web: {}, lynx: {}, }, }); ``` 官方文档明确给了这个写法: ```ts import { defineConfig } from '@lynx-js/rspeedy'; import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin'; export default defineConfig({ plugins: [pluginReactLynx()], environments: { web: {}, lynx: {}, }, }); ``` 来源:https://lynxjs.org/zh/guide/start/integrate-with-existing-apps.md (「将 Lynx 集成到 Web 平台」章节) `environments` 的语义(API 文档): - 用于设置 output environment。 - **未设置时,Rspeedy 向 Rsbuild 传 `{ lynx: {} }`** —— 这就是为什么默认只产出 `.lynx.bundle`。 - "Normally you don't need this if you are not using Lynx for Web." 来源:https://lynxjs.org/api/rspeedy/rspeedy.config.environments.md **产物文件名**:`output.filename.bundle` 默认值是 **`'[name].[platform].bundle'`**,其中 `[platform]` = "the environment name of the bundle"。所以: | 环境 | 入口名 | 产物 | | --- | --- | --- | | `lynx` | `main` | `dist/main.lynx.bundle` | | `web` | `main` | **`dist/main.web.bundle`** | 来源:https://lynxjs.org/api/rspeedy/rspeedy.filename.bundle.md 官方也明确写了: > 你将会看到项目中多出了 `dist/main.web.bundle` 文件,它就是最终的 web 构建产物。 ### 3.4 你需要的 HTML 页面(必须自己写) **Rspeedy 不生成 HTML。** 官方给的 Web 接入方式是「创建一个新的 web 工程(Rsbuild/React)→ `npm install @lynx-js/web-core` → 在 `App.tsx` 里用 ``」,并且要么用 `server.publicDir` 指向 Lynx 项目的 `dist`,要么把 `.web.bundle` 当作静态资源。 来源:https://lynxjs.org/zh/guide/start/integrate-with-existing-apps.md **最省事方案(单文件、零额外工程):把 `index.html` 放到项目根的 `public/` 目录。** 依据:Rspeedy 的 `public` 目录有两个行为 —— 开发服务器下这些资源被托管在 `/` 根路径;生产构建时被复制到输出目录。并且**不要用 import 引用 public 里的文件,用 URL 绝对路径引用**。 来源:https://lynxjs.org/zh/rspeedy/assets.md 新建 `public/index.html`: ```html Lynx on Web ``` > 这里用的是 **bare specifier** `'@lynx-js/web-core/client'`。浏览器本身不认识这种写法 —— 它能工作是因为 Rspeedy/Rspack 会处理 `public/index.html` 里的 module script 吗?**不会**。所以稳妥起见请用下面两种方式之一: **方式 A(推荐,最稳):用 CDN 的预构建产物** —— `@lynx-js/web-core` 的 `exports` 里提供了已打包好的入口: ```html ``` 依据:`@lynx-js/web-core@0.26.2` 的 package.json `exports` 中含 `"./client.prod.js": { "default": "./dist/client_prod/static/js/client.js" }` 和 `"./client.prod.css": { "default": "./dist/client_prod/static/css/client.css" }`。 来源:https://registry.npmjs.org/@lynx-js%2Fweb-core/latest **方式 B(工程化):独立 Rsbuild/React Web 工程**,按官方文档走: ```bash # 在上述 Lynx 项目同级 npm create rsbuild@latest # 选 React cd npm install npm install @lynx-js/web-core ``` `src/App.tsx`: ```tsx import './App.css'; import '@lynx-js/web-core/client'; import type { LynxViewElement as LynxView } from '@lynx-js/web-core/client'; const App = () => { return ( ); }; export default App; ``` `rsbuild.config.ts`(把 Lynx 项目的 dist 作为 publicDir): ```ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export default defineConfig({ plugins: [pluginReact()], server: { publicDir: [ { name: path.join( __dirname, '../', // 这里请替换为你实际的 Lynx 项目名称 'lynx-project', 'dist', ), }, ], }, }); ``` 然后 `npm run dev` → 访问 `http://localhost:3000`。 来源:https://lynxjs.org/zh/guide/start/integrate-with-existing-apps.md ### 3.5 single-threaded 还是 multi-threaded?需要 `.web.bundle` 吗? **结论:** 1. **需要 `.web.bundle`。** `output.filename.bundle` 默认 `[name].[platform].bundle`,`platform` 取环境名,所以 `environments.web` 产出 `main.web.bundle`。`` 指向的就是它。**.lynx.bundle 不能给 web-core 用**(原生产物经过 `encode` AOT 优化、是二进制字节码,Web 端产物是另一种格式)。 来源:https://lynxjs.org/api/rspeedy/rspeedy.filename.bundle.md 、https://github.com/lynx-family/lynx-stack/blob/main/packages/web-platform/readme.md 2. **不再是 single/multi-threaded 二选一的问题** —— `thread-strategy` 这个属性在 `@lynx-js/web-core@0.20.0` 被**移除**了,同时移除了 `customTemplateLoader`、`overrideLynxTagToHTMLTagMap`、`inject-head-links`。旧版(≤0.19)才有 `thread-strategy`(值是 `multi-thread` / `single-thread` / `all-on-ui`)。 来源:https://lynxjs.org/zh/api/lynx-native-api/lynx-view/lynx-view.md (「从旧版本迁移」章节) 3. **你也不需要为 web-core 单独指定 bundle 类型或加 `.web` 后缀配置** —— 只要 `environments.web` 存在,Rspeedy 就按 web 目标编译,产物自然带 `.web`。 4. 早期那个 `Uncaught SecurityError: Failed to construct 'Worker': Script at 'xxx' cannot be accessed from origin 'xxx'` 报错(跨域 Worker)来自多线程架构。文档仍保留了这条 FAQ,解决方式是引入 `remote-web-worker`(且必须在 `@lynx-js/web-core` **之前**引入)。在同源部署 + 当前版本下一般不会遇到,但要知道有这么个东西。 来源:同上 FAQ 章节 --- ## 4. Rspeedy dev server:端口、命令、是否产出 HTML | 问题 | 答案 | 依据 | | --- | --- | --- | | 启动命令 | `rspeedy dev`,脚手架里是 `npm run dev` | https://lynxjs.org/zh/rspeedy/cli.md | | 默认端口 | **3000**(Rsbuild 默认值) | https://lynxjs.org/api/rspeedy/rspeedy.server.port.md | | 端口被占用 | 默认**自动递增**端口号,直到找到可用端口 | 同上 + `server.strictPort` | | 自定义端口 | `server: { port: 3470 }` | 同上 | | 是否产出可访问的 HTML | **否**。Rspeedy 产物只有 bundle / js / 静态资源,**没有 HTML**。`` 所在的 HTML 要自己写 | https://lynxjs.org/zh/rspeedy/output.md 、 §3.4 | | dev 产物写盘 | `dev.writeToDisk` 默认为 **`true`**,但**通过浏览器访问的 bundle 仍从内存提供**(走 webpack-dev-middleware) | https://lynxjs.org/api/rspeedy/rspeedy.dev.writetodisk.md | | 生产预览 | `rspeedy preview`(需先 `rspeedy build`;官方说不要用于生产服务器) | https://lynxjs.org/zh/rspeedy/cli.md | ### 4.1 Rspeedy CLI 全貌 ```text Usage: rspeedy [options] Commands: build [options] Build the project in production mode dev [options] Run the dev server and watch for source file changes while serving. inspect [options] View the Rsbuild config and Rspack config of the project. preview [options] Preview the production build outputs locally. help [command] display help for command ``` 常用参数:`--environment `(只构建指定环境)、`--base `、`-m --mode`、`-c --config`。 `rspeedy dev` 的 dev server 配置在 `dev` 段(`hmr` / `liveReload` / `assetPrefix` / `writeToDisk` / `watchFiles` / `progressBar`),`server` 段管 host/port/base/proxy/cors/headers。 ### 4.2 开发环境产物结构(`dist/.rspeedy`) ```text dist/ ├── .rspeedy │ ├── async/[name]/{debug-metadata.json,tasm.json,[name].css} │ ├── [name]/ │ │ ├── background.js # 后台线程脚本 │ │ ├── main-thread.js # 主线程脚本 │ │ ├── debug-metadata.json │ │ ├── [name].css │ │ └── tasm.json │ └── rspeedy.config.js ├── [name].lynx.bundle └── static/{image,js}/... ``` 来源:https://lynxjs.org/zh/rspeedy/output.md ### 4.3 完整可跑的流程 ```bash # 0) Node 版本检查(必须 ^20.19.0 || >=22.12.0) node -v # 1) 脚手架 npm create rspeedy@latest my-lynx-app cd my-lynx-app npm install # 2) 改 lynx.config.ts,加 environments: { lynx: {}, web: {} } # 3) 新建 public/index.html(内容见 §3.4,用 CDN 版 client.prod.js) # 4) 起 dev server npm run dev # → 终端打印 http://localhost:3000 # 5) 浏览器打开 # http://localhost:3000/index.html # ( 会去拉 http://localhost:3000/main.web.bundle) # 6) 生产构建 + 本地预览 npm run build # 产出 dist/main.lynx.bundle 和 dist/main.web.bundle npx rspeedy preview # 预览产物 ``` **关于「必须自己写 index.html」的替代品**:官方提供了一个现成的在线预览器 —— [Lynx Explorer Web 版](https://www.unpkg.com/@lynx-js/web-explorer@latest/index.html),把你产物可访问的 URL 填进去就能看生产模式下的效果,不用自己写 HTML。适合快速验证产物是否正确。 来源:https://lynxjs.org/zh/guide/start/integrate-with-existing-apps.md --- ## 5. 样式系统约束 ### 5.1 display 与布局:不是「只支持 flex」 Lynx 里 `display` 支持 **5 个值**:`linear`、`flex`、`grid`、`relative`、`none`。 | 值 | 对应 Web | 说明 | | --- | --- | --- | | `linear` | 无直接对应(近似更简化的 Flex) | **Lynx 的默认布局**。主轴默认竖向,用 `linear-direction`、`linear-weight` 控制 | | `flex` | CSS Flexbox | 绝大部分属性一致;**当前不支持 `min-content`**,子项收缩下限视作 `0px` | | `grid` | CSS Grid | 支持常见行列定义与 gap;暂不支持 `grid-area`、line names | | `relative` | Android RelativeLayout 心智 | **仅移动端有效**;用 `relative-*` 描述与兄弟/父节点的相对定位 | | `none` | — | 不参与布局 | 所以准确说法是:**默认(`linear`)也受 `align-items` / `justify-content` 等对齐属性控制,但不要假设 Web flex 的默认值**。要 flex 行为就显式写 `display: 'flex'`。 - 所有元件默认 `box-sizing: border-box`,**且不具备 margin collapsing(外边距折叠)**。 ⚠️ 与 Web 不一致:`width`/`height`/`max-width` 等描述的是**含边框大小**(包含 border 与 padding)。 - **不存在 `inline` / `block` 切换**,`display` 不接受这两个值。文本布局依赖 `` 元件。 - 逻辑方向属性(`inset-inline-start` 等)**依赖 `direction` 且需要开启 CSS 继承功能**才可用。 - `` 元件内**不能直接插入文字**。 来源:https://lynxjs.org/zh/guide/ui/layout/index.md 、https://lynxjs.org/zh/guide/ui/layout/linear-layout.md 、https://lynxjs.org/zh/llms.txt ### 5.2 长度单位 | 单位 | 语义 | | --- | --- | | `px` | 像素,等于「一物理像素 × 像素密度」,相当于 iOS 的 `pt` / Android 的 `dp`。高分辨率屏上一个 CSS px 往往占多个设备像素。约 96/英寸 | | `ppx` | 物理像素(physical pixel),等于屏幕一实际像素的大小 | | `rpx` | responsive pixel,按屏幕宽度自适应。**规定屏幕宽为 750rpx**。iPhone6 上屏宽 375px、共 750 个物理像素 ⇒ **750rpx = 375px = 750 物理像素,即 1rpx = 0.5px = 1 物理像素** | | `%` | 相对于父元件 | | `vw` / `vh` | 视口初始包含块宽度 / 高度的 1% | | `rem` | 根元件的 `font-size` 大小;用在根元件 `font-size` 上时代表其初始值 | | `em` | 元件的 `font-size` 计算值;用在 `font-size` 属性本身时表示继承来的 `font-size` | **`0` 以外的数字必须带单位**,不支持无单位写法。 来源:https://lynxjs.org/zh/api/css/data-type/length.md ### 5.3 选择器支持范围 **支持:** - 类型选择器 `view {}`、类选择器 `.a {}`、多类 `.a.b {}`、ID `#id {}`、通配 `* {}` - 组合器:后代(空格)、子代 `>`、后续兄弟 `~`、紧邻兄弟 `+`、选择器列表 `,` - 伪类:**仅 4 个** —— `:not()`、`:root`、`:active`、`:hover` - 伪元素:**仅 `::selection`** **关键差异 / 不支持:** - 根节点选择器是 **`page`,不是 `body`**。(`:root` 也可用来匹配根节点) - `:hover` 平台差异大:**Web 支持**(用浏览器原生 `:hover` 实现);Clay macOS/Windows 自 3.7 起支持;经典 Android/iOS/HarmonyOS 和 Clay iOS **不支持**。 - `::before` / `::after` **不在支持列表里**。 - `:first-child` / `:nth-child` 等**未在支持列表中**。 - `!important` **默认不支持**;从 `engineVersion 3.9` 起可在插件选项里把 `engineVersion` 设为 `'3.9'` 或更高来启用。 - 属性选择器 `[data-x]` **文档未列出**,不要依赖。 来源:https://lynxjs.org/zh/api/css/selectors.md ### 5.4 CSS 继承(默认不继承!) - **常规(非自定义)CSS 属性默认不继承**,需要配置 `enableCSSInheritance` 开启。 - 开启后**默认只有这些属性可继承**:`direction`、`color`、`font-family`、`font-size`、`font-style`、`font-weight`、`letter-spacing`、`line-height`、`text-align`、`text-decoration`、`text-shadow`。 - 想加更多用 `customCSSInheritanceList`,例如 `"customCSSInheritanceList": ["font-size", "flex-direction"]`。**注意:一旦声明了这个列表,就只有列表里的属性可继承**。 - **CSS 变量(`--*`)默认可继承,无需配置**(遵循 Web 标准)。 - 继承的三个局限: 1. `position: fixed` 的元件**永远只继承 page 的属性**; 2. **不支持关键字 `inherit`**; 3. 除默认可继承属性外,只有类型为**枚举或布尔值**的 CSS 属性支持自定义继承。 来源:https://lynxjs.org/zh/guide/styling/custom-theming.md#按需使用-css-继承 在 `lynx.config.ts` 里开启: ```ts import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin'; import { defineConfig } from '@lynx-js/rspeedy'; export default defineConfig({ plugins: [ pluginReactLynx({ enableCSSInheritance: true, customCSSInheritanceList: ['font-size', 'flex-direction'], }), ], }); ``` ### 5.5 CSS 变量 `--*` **完整支持**,Web 端也标 ✅ Yes。 - 声明:选择器里 `:root { --main-bg-color: yellow; }`,或内联 `style={{ '--main-bg-color': 'yellow' }}`。 - 引用:`background-color: var(--main-bg-color)`;支持嵌套引用 `--b: var(--a)`。 - 默认值:`width: var(--view-width, 100px)`。 - 与 `calc()` 配合:`height: calc(var(--main-height) - 100px)`(变量声明里不能直接做数学运算)。 - JS 改值:`lynx.getElementById('root').setProperty({ '--color': 'white', '--bg': 'black' })`(参数必须是 Object 或 String)。 - ⚠️ **坑**:用 JS `setProperty` 改过变量之后,**再切 class 就不会生效了**(官方示例里专门做了个错误提示:"Cannot change variables through the class after modifying them in JS!")。 来源:https://lynxjs.org/zh/api/css/properties/css-variable.md 主题切换两种官方写法(推荐 CSS 变量那种,更灵活): ```tsx // 方式一:后代选择器切 class Hello Theme // 方式二:CSS 变量 + 切顶层 class // .theme-light { --color: black; --bg: white; } // .theme-dark { --color: white; --bg: black; } // .content { color: var(--color); background-color: var(--bg); } Hello Variable ``` ### 5.6 `overflow` / `position` - **不支持 `overflow: scroll` 做滚动**。`` 没有滑动效果,只有 `` 和 `` 等滑动容器有。 - `overflow` 可以用于**裁切**溢出内容(如 `overflow: hidden`)。 - `position` 支持 **3 种**:`relative`、`absolute`、`fixed`。**`fixed` 的节点会被直接提升为根节点的直接子节点**。 来源:https://lynxjs.org/zh/guide/ui/scrolling.md 、https://lynxjs.org/zh/llms.txt ### 5.7 文本:必须包在 `` 里 ```tsx // ❌ 不会生效 hello world // ✅ hello world ``` - 行内混排靠**嵌套 ``**: ```tsx This is an important word ``` - `` 里**还可以嵌套 ``** 和 `` 做图文混排(`` 在行内用 `vertical-align` 调垂直位置;`` 底部默认与文本基线对齐)。 - 文本截断:`text-maxline` + `text-overflow: ellipsis`;自定义截断处内容用 ``。 - 文本装饰:`text-shadow`、`text-stroke`(`textStroke` 类型尚未进 `@lynx-js/types`,示例里用了 `@ts-expect-error`)、`text-indent`、`word-break`、`text-align`、`line-height`。 - 字体:支持 `@font-face` 和 `lynx.addFont`,但**宿主需实现字体资源加载器**(原生侧)。Web 端由浏览器处理。 来源:https://lynxjs.org/zh/guide/styling/text-and-typography.md ### 5.8 `class` vs 内联 `style` - **JSX 里用 `className`**(``);纯模板语法里写 `class`。两者都能让类选择器命中。 - **内联 `style` 支持对象**:`style={{ color: 'red', '--x': '1px' }}`;纯模板语法里写字符串:`style="width:200px;height:100px"`。 - 优先级遵循 CSS 层叠:**内联 `style` 覆盖样式规则**,权重高的选择器覆盖权重低的,文档中后出现的规则覆盖先出现的。 - 单个类名下也支持嵌套语法(Sass / postcss-nesting)。 来源:https://lynxjs.org/zh/guide/ui/styling.md 、https://lynxjs.org/zh/guide/ui/elements-components.md ### 5.9 `` 用法 - **空元件**,不支持子节点。 - 要显示图片,`src` 非空**且**满足以下之一:宽高都 > 0 **或** `auto-size`。 - `mode` 取值(默认 `scaleToFill`):`scaleToFill` | `aspectFit` | `aspectFill` | `center`。 - 支持格式:`png`、`jpg`、`jpeg`、`bmp`、`gif`、`webp`。**不支持 svg**(要 SVG 得自己写自定义元件;或用 `` 元件)。 - 本地图片:`import logo from './assets/logo.png'` → 返回**表示静态资源的 URL 字符串**,直接传给 `src`。小于阈值(默认 **2KiB**)会自动内联为 base64。 - `?inline` 强制内联;`?url` 强制不内联。 - 类型声明来自 `src/lynx-rspeedy-env.d.ts` 里的 `/// `。 - URL 前缀:dev 用 `dev.assetPrefix`,生产用 `output.assetPrefix`。 - 其他属性:`placeholder`、`blur-radius`、`prefetch-width`/`prefetch-height`、`cap-insets`、`tint-color`、`image-config`(Android)。 - 事件:`bindload`(`e.detail` 有 `width`/`height`)、`binderror`。 来源:https://lynxjs.org/zh/api/elements/built-in/image.md 、https://lynxjs.org/zh/rspeedy/assets.md ### 5.10 `` 用法 ⚠️ **注意**:官方 quick-start 的旧摘要里说「通过指定 `scroll-y` 或 `scroll-x` 属性之一来启用滚动」,但**当前 `` API 文档里没有 `scroll-x`/`scroll-y` 这两个属性**,用的是 **`scroll-orientation`**。以 API 文档为准: ```tsx {/* 直接子节点只支持 linear 与 sticky */} ``` - `scroll-orientation`:`vertical`(默认)| `horizontal`。**它同时决定滚动方向和子节点布局方向**。 - `` **固定使用 linear 布局**。 - **必须给它一个确定的高度(或宽度)** —— 它本身不靠内容撑开。 - ⚠️ **直接子节点只支持 `linear` 与 `sticky`**。需要复杂布局时,**给它一个唯一的子 ``,在里面随便写**: ```tsx {/* 随便写 */} ``` - 其他属性:`enable-scroll`(默认 `true`)、`initial-scroll-offset`、`initial-scroll-to-index`(两者互相覆盖,不能一起用)、`bounces`(默认 `true`)、`upper-threshold`、`lower-threshold`、`scroll-bar-enable`(默认 `false`)、`sticky`(只能给直接子节点;Android 上还需 `flatten={false}`)。 - 事件:`bindscroll`、`bindscrolltoupper`、`bindscrolltolower`、`bindscrollend`、`bindcontentsizechanged`。 - 方法(走 `SelectorQuery` + `.invoke()` + `.exec()`):`scrollTo`、`autoScroll`、`scrollIntoView`、`scrollBy`。 - **性能**:`` 会**一次性创建所有子节点**,且**没有任何复用机制**。数据超过 3 屏时优先用 ``。 来源:https://lynxjs.org/zh/api/elements/built-in/scroll-view.md ### 5.11 不支持的 CSS 特性速查(避坑清单) | 特性 | 状态 | | --- | --- | | `overflow: scroll` / `auto` 做滚动 | ❌ 用 `` / `` | | `display: inline` / `block` | ❌ 不支持这两个取值 | | margin collapsing(外边距折叠) | ❌ 不存在 | | `box-sizing` 默认值 | ⚠️ 固定 `border-box`,且 width 含 border+padding | | `min-content` | ❌ flex 下不支持 | | `!important` | ⚠️ 默认不支持,需 `engineVersion >= '3.9'` | | `inherit` 关键字 | ❌ 不支持 | | `::before` / `::after` | ❌ 不在支持列表(仅 `::selection`) | | `:first-child` / `:nth-child` | ❌ 未列出 | | `:hover` | ⚠️ Web ✅、移动端经典渲染器 ❌ | | `@font-face` | ✅ 但宿主需实现字体加载器 | | `@media` | 文档未提及支持 | | CSS 变量、`calc()`、`transform`、`linear-gradient`、`radial-gradient`、`border-radius`、`text-shadow` | ✅ 支持(官方示例中大量使用) | | `display: grid` 的 `grid-area` / line names | ❌ 暂不支持 | | 普通属性的 CSS 继承 | ⚠️ 默认关闭,需 `enableCSSInheritance` | 来源:https://lynxjs.org/zh/guide/ui/layout/index.md 、https://lynxjs.org/zh/api/css/selectors.md 、https://lynxjs.org/zh/guide/ui/scrolling.md 、https://lynxjs.org/zh/llms.txt 、https://lynxjs.org/zh/api/css/properties/css-variable.md --- ## 6. ReactLynx 与 React 的差异 ### 6.1 基线:React 17 API + Preact 实现 - ReactLynx 是 React 的一个实现,**本质上基于 Preact**;可以用 `react` 换 `@lynx-js/react` 的方式迁移。 - **以 React 17 API 作为基础**。官方明确说明了原因:React 18 起的「并发 React 功能」(`useTransition`、`useDeferredValue`)对执行环境的调度方式和并发模型要求苛刻(依赖/覆写浏览器 Web API 等),Lynx 选 React 17 作基石。 注意 `@lynx-js/react` 的 `dependencies` 里写的是 `"preact": "npm:@lynx-js/internal-preact@11.0.0-rc.1-..."` —— Preact 被 alias 成了 Lynx 内部 fork。 来源:https://lynxjs.org/zh/api/react/index.md 、https://lynxjs.org/zh/react/introduction.md 、https://registry.npmjs.org/@lynx-js%2Freact/latest ### 6.2 支持的 hooks / API 清单(来自官方 API 索引) **Hooks(全部可用):** `useCallback`、`useContext`、`useDebugValue`、`useEffect`、`useImperativeHandle`、`useMemo`、`useReducer`、`useRef`、`useState`、`useSyncExternalStore` **Lynx 特有:** `useMainThreadRef`、`useGlobalProps`、`useGlobalPropsChanged`、`useInitData`、`useInitDataChanged`、`useLynxGlobalEventListener` **其他 API:** `cloneElement`、`createContext`、`createElement`、`createPortal`、`createRef`、`forwardRef`、`Fragment`、`isValidElement`、`lazy`、`memo`、`Suspense`、`Component`、`PureComponent`、`runOnBackground`、`runOnMainThread`、`withInitDataInState`、`root`、`useErrorBoundary` 组件级:`GlobalPropsProvider`/`GlobalPropsConsumer`、`InitDataProvider`/`InitDataConsumer` **不支持:** `useLayoutEffect`(见下)、`useId`、`useTransition`、`useDeferredValue`、`useOptimistic`、`useActionState`(并发时代的 API 一律没有)。 来源:https://lynxjs.org/zh/api/react/index.md ### 6.3 `useLayoutEffect` —— 别名,不是真禁用 文档里有两处说法,以 API 参考为准: - API 参考:**`useLayoutEffect` is now an alias of `useEffect`. Use `useEffect` instead.** - 生命周期指南:所有生命周期钩子都在**后台线程异步执行**,不具备同步阻塞渲染的特性,因此 ReactLynx **不支持 `useLayoutEffect`**。 - 替代方案:用元件的 **`main-thread:bindlayoutchange`** 事件获取布局结果并设置属性;或 `main-thread:ref` + `MainThread.Element.invoke('boundingClientRect')`。 ```tsx const handleLayoutChange = (e: any) => { "main thread"; e.currentTarget.setStyleProperty("transform", `translate3d(${x}px, ${y}px, 0)`); }; // ``` 来源:https://lynxjs.org/zh/react/lifecycle.md 、https://lynxjs.org/zh/api/react/index.md 、https://lynxjs.org/zh/llms.txt ### 6.4 `useEffect` 可用,但在后台线程 - **可用**,在**后台线程**执行,效果在「主线程 DOM 更新之后」运行且不阻塞它。 - 在 `useEffect`、`useImperativeHandle`、ref 回调、事件处理函数里调用 `NativeModules` / `lynx.getJSModule` 等原生 API 是**安全的**(因为都在后台线程)。 - 在**组件渲染逻辑/顶层**调用原生 API 会被标为**关键**错误 —— 那跑在主线程上,会阻塞 UI。 ```tsx // ❌ 组件顶层调用原生 API function App() { const data = NativeModules.Storage.get('key'); return {data}; } // ✅ 放 useEffect useEffect(() => { setData(NativeModules.Storage.get('key')); }, []); // ✅ 或用 'background only' 标记 function fetchData() { 'background only'; return NativeModules.Storage.get('key'); } ``` 来源:https://lynxjs.org/zh/react/best-practices.md ### 6.5 事件绑定:`bindtap`,不是 `onClick` **没有 `onClick`。** 命名规则:`bind*` / `catch*` / `capture-bind*` / `global-bind*`,主线程版加 `main-thread:` 前缀。 | 写法 | 行为 | | --- | --- | | `bindtap` | 冒泡到父节点 | | `catchtap` | **拦截**,不再继续传播 | | `capture-bindtap` | 捕获阶段 | | `global-bindtap` | 跨元件监听(任意节点被点时都能收到);可用 `global-target` 限定只监听某些 `id` | | `main-thread:bindtap` | 在主线程处理 | ```diff -