> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# 从源码到 Bundle

Lynx 使用 [Rsbuild](https://rsbuild.rs/zh/) 和 [`pluginLynx`] 构建应用。你可以沿用 Rsbuild 的 TypeScript、CSS、静态资源和插件能力，由 `pluginLynx` 完成双线程编译和 Bundle 编码，生成宿主可以加载的产物。

## 使用 Rsbuild 开始 \{#getting-started}

用 ReactLynx 的 Rsbuild 模板创建项目：

```bash
npm create @lynx-js/lynx@latest -- --template rsbuild-react-ts
```

进入生成的项目目录，安装依赖并启动开发服务器：

```bash
npm install
npm run dev
```

用 [Lynx Explorer](/next/zh/guide/start/quick-start.md) 扫描二维码，即可在设备上运行应用。开发服务器会在保存代码后更新应用。

模板的构建配置写在 `rsbuild.config.ts` 中。[`pluginReactLynx`](/next/zh/api/packages/react-rsbuild-plugin/functions/pluginReactLynx.md) 会自动应用 `pluginLynx`，[`pluginQRCode`](/next/zh/api/packages/qrcode-rsbuild-plugin.md) 提供扫码入口：

```ts title="rsbuild.config.ts"
import { pluginQRCode } from '@lynx-js/qrcode-rsbuild-plugin';
import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin';
import { defineConfig } from '@rsbuild/core';

export default defineConfig({
  source: {
    entry: {
      main: './src/index.tsx',
    },
  },
  plugins: [pluginQRCode(), pluginReactLynx()],
});
```

开发完成后，使用 `rsbuild build` 生成生产产物，使用 `rsbuild preview` 在本地预览。

### 配置应用

`rsbuild.config.ts` 接受完整的 [Rsbuild 配置](https://rsbuild.rs/zh/config/)。你可以按项目需要配置：

- 
  **[TypeScript](/next/zh/guide/build/typescript.md)**：构建时的类型声明，以及应用数据、元件和原生模块的类型扩展。
- 
  **[CSS](/next/zh/guide/build/styling.md)**：CSS Modules、全局样式、预处理器和 PostCSS；使用
  Tailwind 时，参见 [Lynx preset 的配置](/next/zh/guide/build/styling.md#tailwind-css)。
- 
  **[静态资源](https://rsbuild.rs/zh/guide/basic/static-assets)**：图片、字体和
  `public/` 目录，以及资源的 URL 前缀和内联方式。
- 
  **[模块解析](https://rsbuild.rs/zh/config/resolve/alias)**：路径别名和依赖解析。`pluginLynx`
  会优先选择依赖的 `lynx` 导出条件，文件扩展名规则见
  [`resolve.extensions`](/next/zh/api/build/resolve/extensions.md)。
- 
  **[插件](https://rsbuild.rs/zh/plugins/list/)**：接入 Rsbuild 插件，或通过
  `tools.rspack` 扩展底层构建流程。

Lynx 新增的配置项和调整过的默认值见 [`rsbuild.config.ts` 参考](/next/zh/api/build.md)。例如，要自定义 Bundle 文件名，可以在 `plugins` 中显式添加 `pluginLynx({ output: { filename: { bundle: 'app.lynx.bundle' } } })`；它不会被重复应用。

### 优化与调试

构建也提供了控制加载方式、分析性能和定位问题的入口：

- **[代码分割](/next/zh/react/code-splitting.md)**：让部分代码按需加载，减小首屏需要加载的产物。
- 
  **[External
  Bundle](/next/zh/guide/build/external-bundle.md)**：把公共依赖构建为多个应用可以共享的 Bundle。
- **[构建性能分析](https://rsbuild.rs/zh/guide/debug/build-profiling)**：通过 Rsdoctor 等工具了解构建耗时和依赖关系。
- 
  **[运行时性能](/next/zh/guide/performance/analysis-performance/analysis-framework.md)与[产物体积](/next/zh/guide/performance/analysis-performance/analysis-bundle-size.md)**：分析应用运行和加载的成本。
- **[线上错误反解](/next/zh/guide/devtool/map-errors-to-source.md)与 [UI Source Map](/next/zh/guide/devtool/ui-source-map.md)**：利用构建生成的调试信息，将错误和运行中的节点映射回源码。

:::info 仍在使用 Rspeedy？
Rspeedy 仍在维护，与 `pluginLynx` 使用同一套构建引擎。现有项目可以继续使用；新项目推荐使用 Rsbuild。两者的区别和迁移步骤见 [Rspeedy 迁移指南](/next/zh/guide/build/rspeedy.md#migrating-an-rspeedy-project)。
:::

## 理解产物 \{#bundles}


[_**Lynx Bundle**_][Lynx Bundle] 是 Lynx 应用的交付产物：一个后缀为
`.lynx.bundle` 的二进制文件。容器拿到它的 URL 或内容，交给 [_**Lynx
Engine**_][Lynx Engine] 加载，页面就渲染出来了。Lynx Bundle 和 Web
应用其实非常像：



| 组成 | Web 应用                     | Lynx Bundle                                       |
| -- | -------------------------- | ------------------------------------------------- |
| 脚本 | JavaScript 文件，运行时加载        | 默认编码进 Bundle；**主线程**代码创建**首屏**元素，**后台线程**代码运行业务逻辑 |
| 样式 | CSS 文件，运行时加载               | CSS 解析为结构化数据，编码进 Bundle                           |
| 资源 | 图片、字体等独立文件，小资源可以内联         | 同样支持独立文件和小资源内联                                    |
| 入口 | 浏览器加载 HTML，再加载它引用的脚本、样式和资源 | 容器直接加载 Bundle，包含页面配置等元信息                          |

### 输出文件 \{#output-files}

#### 标准 Lynx Bundle 产物

构建产物默认写入 `dist/`：

```txt
dist/
├── [name].lynx.bundle  # 应用 Bundle
├── lazy-bundle/       # 按需加载的 Bundle
├── static/            # 静态资源和分包脚本
└── .lynx/[name]/      # 调试用中间产物
```

脚本默认编码进 Bundle，开启代码分包后也会输出到 `static/js/`。通过 [`output.filename.bundle`](/next/zh/api/build/output/filename/bundle.md) 设置 Bundle 文件名，[`output.filename`](https://rsbuild.rs/zh/config/output/filename) 设置其他文件名，[`output.distPath`](/next/zh/api/build/output/dist-path.md) 调整输出目录；[Source Map](/next/zh/api/build/output/source-map.md) 和[许可声明](/next/zh/api/build/output/legal-comments.md)的配置见对应 API。

#### Web 产物

同一份源码也可以构建到 Web：`web` 环境产出 `.web.bundle`，由 `<lynx-view url="...">` 加载。默认文件名中的 `[platform]` 对应环境名，因此两种环境分别生成 `main.lynx.bundle` 和 `main.web.bundle`。

#### 从中间产物到二进制

构建先生成**主线程**脚本 `main-thread.js`、**后台线程**脚本 `background.js` 和样式，再由 `tasm.json` 组织这些内容及页面配置，交给 [`@lynx-js/tasm`](https://www.npmjs.com/package/@lynx-js/tasm) 编码为 `.lynx.bundle` 二进制文件。

这些中间产物保存在 `.lynx/[name]/`，默认只在开发构建时保留；生产构建可通过 `DEBUG=lynx` 保留。查看 `tasm.json` 可以了解 Bundle 编码了哪些内容；`debug-metadata.json` 用于[线上错误反解](/next/zh/guide/devtool/map-errors-to-source.md)。

### 一个应用可以有多个 Bundle

主 Bundle 之外，还可以按需加载或共享其他 Bundle：

- **懒加载 Bundle**：通过动态 `import()` 加载组件，产物输出到 `lazy-bundle/`，减少**首屏**需要加载的内容。详见[代码分割](/next/zh/react/code-splitting.md)。
- **External Bundle**：把公共依赖单独构建为 Bundle，供多个应用共享。详见 [External Bundle](/next/zh/guide/build/external-bundle.md)。

## 兼容性 \{#compatibility}

本文主要介绍如何确保 [Bundle] 和 [Lynx Engine] 之间的版本兼容性，以及如何应对 Lynx Engine 版本演进带来的挑战。

### 从源码构建

一种简单的保证兼容性的方法是，**永远同时从源码构建 Bundle 和宿主应用**。

- Bundle 可以充分利用当前 Lynx Engine 版本的所有特性
- 在开发阶段就能完全确保兼容性，所见即所得

### 多版本兼容

但是在一个复杂的工程中，Bundle 和 Lynx Engine 之间并非一一对应的关系

- 一个 Bundle 可能运行在多个含有不同版本 Lynx Engine 的应用中

- 一个应用中也可以运行多个由不同团队维护的 Bundle

此时，需要为 Bundle 设置**引擎版本**（[`engineVersion`]）来保证兼容性

:::info 引擎版本

当 Bundle 的引擎版本大于 Lynx Engine 版本时，将无法运行

:::

例如：一个 [`engineVersion`] 为 3.3 的 Bundle 可以在 Lynx Engine 3.3 及以后的版本上运行，但不能在 3.2 上运行。

**版本兼容性示意图** 

graph TB
  subgraph Bundle["🎯 Bundle"]
      B10["引擎版本 3.3"]
  end
  subgraph Engine["⚙️ Lynx Engine"]
      E12["Version 3.5"]
      E11["Version 3.4"]
      E10["Version 3.3"]
      E09["Version 3.2"]
  end
  B10 -.->|❌ 不支持| E09
  B10 ==>|✅ 可运行| E10
  B10 ==>|✅ 可运行| E11
  B10 ==>|✅ 可运行| E12
  %% 节点样式
  style E12 fill:#2b5a83,stroke:#4a90e2,stroke-width:3px,rx:10px
  style E11 fill:#2b5a83,stroke:#4a90e2,stroke-width:3px,rx:10px
  style E10 fill:#2b5a83,stroke:#4a90e2,stroke-width:3px,rx:10px
  style E09 fill:#2b5a83,stroke:#4a90e2,stroke-width:2px,rx:10px,stroke-dasharray:5,5
  style B10 fill:#2d5a1e,stroke:#7ed321,stroke-width:3px,rx:10px
  %% 子图样式
  style Bundle fill:transparent,stroke:#7ed321,stroke-width:2px,rx:10px
  style Engine fill:transparent,stroke:#4a90e2,stroke-width:2px,rx:10px
  %% 默认样式
  classDef default fill:#23272f,color:#ccc,font-family:system-ui
  %% 连接线标签样式
  linkStyle default stroke-width:2px

在一个 Bundle 对应多个 Lynx Engine 版本的情况下，该 Bundle 的 [`engineVersion`] 不能高于其中最低的 Lynx Engine 版本。

在一个 Lynx Engine 版本上运行多个 Bundle 的情况下，每个 Bundle 都可以设置不同的 [`engineVersion`]，但是都不能大于 Lynx Engine 的版本

#### 版本不兼容处理

当 Bundle 尝试在一个较低版本的 Lynx Engine 上运行时，系统会抛出错误码为 [10204](/next/zh/api/errors/error-code.md#10204-e_app_bundle_load_parse_failed) 的 Fatal 级别错误，并停止渲染流程。这种机制可以防止不兼容版本导致的潜在运行时问题。

#### 设置引擎版本

[`engineVersion`] 是一个含有两位版本号的字符串，可以在配置文件中指定：

```ts title="rsbuild.config.ts"
import { defineConfig } from '@rsbuild/core';
import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin';

export default defineConfig({
  plugins: [
    pluginReactLynx({
      engineVersion: '3.2',
    }),
  ],
});
```

### 升级 Lynx Engine

Lynx Engine 的迭代过程中，会有新增功能，也会有废弃功能，它们的兼容性也由 [`engineVersion`] 来保证。

#### 新增功能

一些新增功&#x80FD;_**不会**_&#x5BF9;已有的 Bundle 产生影响，但如果 [`engineVersion`] 小于其被引入的版本，则需要在运行时进行判断，例如：

```js
// Detect if `lynx.newlyAddedMethod` can be called
if (lynx.newlyAddedMethod) {
  lynx.newlyAddedMethod();
}
```

而一些新增功能完全无法运行在低版本的 Lynx Engine 中，因此它们只有在 [`engineVersion`] 大于或等于对应版本时才会被启用。

#### 废弃功能

一些功能也可能在迭代的过程中被废弃，他们的行为可能在设置了更高的 [`engineVersion`] 后发生改变。

- 如果只升级 Lynx Engine 的版本，不升级 Bundle 的 [`engineVersion`]，那么不会有兼容性问题产生
- 如果同时升级了 Lynx Engine 和 Bundle 的 [`engineVersion`]，需要阅读 CHANGELOG 来确保没有产生预期外的行为变更


### 特性与 API 兼容性 \{#feature-compatibility}

平台特性、元件、API 和 CSS 属性的支持情况可在各自的参考页查看。下例展示 CSS `gap` 的跨平台兼容性：

APISummary

**Compatibility Table**

**Query:** `css.properties.gap`

[Source](https://github.com/lynx-family/lynx/blob/develop/tools/css_generator/css_defines/205-gap.json) · [API Reference](/next/api/css/properties/gap) · [MDN](https://developer.mozilla.org/zh-CN/docs/Web/CSS/gap)

| Feature | Android | HarmonyOS | iOS | macOS | Windows | Web |
| --- | --- | --- | --- | --- | --- | --- |
| gap | Yes (2.14) | Yes (3.4) | Yes (2.14) | Yes (2.14) | Yes (2.14) | Yes |
| Flex | Yes (2.14) | Yes (3.4) | Yes (2.14) | Yes (2.14) | Yes (2.14) | Yes |
| Grid | Yes (2.14) | Yes (3.4) | Yes (2.14) | Yes (2.14) | Yes (2.14) | Yes |

**`gap`**

**Specifications:**

**`Flex`**

Supported in Flexible Box Layout

[Source](https://github.com/lynx-family/lynx/blob/develop/tools/css_generator/css_defines/205-gap.json)

**`Grid`**

Supported in Grid Layout

[Source](https://github.com/lynx-family/lynx/blob/develop/tools/css_generator/css_defines/205-gap.json)


[Bundle]: /next/zh/guide/spec.md#lynx-bundle-or-bundle

[Lynx Bundle]: /next/zh/guide/spec.md#lynx-bundle-or-bundle

[Lynx Engine]: /next/zh/guide/spec.md#engine

[`pluginLynx`]: /next/zh/api/packages/rsbuild-plugin.md

[`engineVersion`]: /next/zh/api/packages/react-rsbuild-plugin/interfaces/PluginReactLynxOptions.md#engineversion
