将 Lynx 集成到 Web 平台

Lynx for Web

Lynx for Web 在 Web 浏览器中实现了 Lynx 引擎。通过 Lynx for Web,你可以轻松地将 Lynx 应用集成到任何现有的 Web 项目中,无论该项目使用的是 React、Vue、Svelte 还是纯 HTML。

1. 构建 web 产物

我们需要你已经阅读并按照快速开始创建了一个 Lynx 项目。

添加 web 配置

  1. 进入 Lynx 项目:
cd <lynx-project-name>
  1. lynx.config.ts 增加 web 配置(environments.web):
import { defineConfig } from '@lynx-js/rspeedy';
import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin';

export default defineConfig({
  plugins: [pluginReactLynx()],
  environments: {
    web: {
      output: {
        assetPrefix: '/',
      },
    },
    lynx: {},
  },
});

构建

执行:

npm
yarn
pnpm
bun
npm run build

你将会看到项目中多出了 dist/main.lynx.bundle 文件,它就是最终的 web 构建产物。

2. 接入 web 项目

目前你已经有了一份 Lynx for Web 构建产物,接下来我们需要创建一个 web 工程去使用它,这里使用 Rsbuild。

创建一个 web 项目

在上述的 Lynx 项目同级,创建一个新的工程,执行:

npm
yarn
pnpm
bun
npm create rsbuild@latest

跟随提示来创建一个 React 项目。

配置工程

  1. 进入 Web 项目:
cd <web-project-name>
  1. 安装依赖:
npm
yarn
pnpm
bun
npm install @lynx-js/web-core @lynx-js/web-elements
  1. src/app.tsx 引入这些依赖:
import './App.css';
import '@lynx-js/web-core/index.css';
import '@lynx-js/web-elements/index.css';
import '@lynx-js/web-core';
import '@lynx-js/web-elements/all';

const App = () => {
  return (
    <lynx-view
      style={{ height: '100vh', width: '100vw' }}
      url="/main.web.bundle"
    ></lynx-view>
  );
};

export default App;
  1. 更新 rsbuild.config.ts
WARNING

server.publicDir 需要更换为你实际的 Lynx 项目路径。

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
yarn
pnpm
bun
npm run dev

访问 http://localhost:3000 即能看到你的 Lynx 应用。

除非另有说明,本项目采用知识共享署名 4.0 国际许可协议进行许可,代码示例采用 Apache License 2.0 许可协议进行许可。