rsx-core
v0.3.1
Published
rust ssr framework for react
Downloads
4
Readme
RSX Core
RSX框架的Node.js/浏览器实现,包含Vite编译器插件、多框架客户端适配器和水合运行时
📋 概述
rsx-core 是RSX框架的Node.js实现,为全栈开发提供完整的工具链和运行时支持:
- ⚛️ React适配器 - React组件的自动渲染和水合
- 🖖 Vue适配器 - Vue组件的支持(规划中)
- 🔥 Svelte适配器 - Svelte组件的支持(规划中)
- 💧 水合运行时 - 浏览器端组件初始化和更新
🚀 快速开始
安装依赖
pnpm install开发服务器
启动带热重载的开发服务器,同时运行Rust后端:
npm run dev
# 或
rsx dev --port 4500 --host localhost服务器将运行在 http://localhost:4500
构建生产版本
npm run build
# 或
rsx build --mode production代码格式化
npm run fmt:js
# 或
rsx fmt --dir ./src代码检查
npm run lint:js
# 或
rsx check --dir ./src📦 主要模块
core/compiler - RSX编译器
将RSX文件编译为可执行的JavaScript模块。
主要功能:
- RSX文件读取和解析
- 使用Tree-sitter生成AST
- 页面和组件的自动分类
- 增量编译和缓存优化
核心类:
export class RsxCompiler {
config: Required<RsxConfig>;
root: string;
pages: RsxFileWithAst[];
components: RsxFileWithAst[];
async loadPages(): Promise<void>;
async build(): Promise<void>;
getPages(): RsxFileWithAst[];
getPage(id: string): RsxFileWithAst | undefined;
getComponents(): RsxFileWithAst[];
getComponent(id: string): RsxFileWithAst | undefined;
}示例:
import { RsxCompiler } from 'rsx-core';
const compiler = new RsxCompiler({
root: process.cwd(),
pages: './src/pages',
output: './dist',
cache: './node_modules/.rsx'
});
await compiler.build();
const pages = compiler.getPages();
const components = compiler.getComponents();core/vite - Vite插件
Vite插件用于在开发和构建过程中处理RSX文件。
主要功能:
- RSX文件转译为JavaScript
- 开发服务器中间件集成
- 服务端HTML获取(SSR)
- 热模块替换支持
使用方式:
import { defineConfig } from 'vite';
import { rsx } from 'rsx-core/vite';
export default defineConfig({
plugins: [rsx()]
});工作原理:
- 在Vite配置解析时初始化编译器
- 配置开发服务器中间件
- 拦截
.rsx文件请求 - 从Rust服务器获取服务端渲染的HTML
- 应用客户端转译
配置项:
interface ViteConfig {
root: string; // 项目根目录
pages: string; // 页面目录
output: string; // 输出目录
cache: string; // 缓存目录
}integration/hydration - 水合运行时
在浏览器端初始化和管理组件,实现服务端渲染与客户端交互的融合。
主要功能:
- 全局状态初始化
- 组件发现和收集
- 多框架渲染器支持
- 属性和事件绑定
- 动态更新机制
使用方式:
import { hydration } from 'rsx-core/client';
// 在应用加载时调用
hydration();
// 更新组件属性
window.$$updateComponent('component-id', { newProp: value });水合流程:
HTML加载
↓
初始化全局状态
↓
收集所有RSX组件
↓
获取服务端属性
↓
为每个组件创建渲染器实例
↓
执行水合
↓
标记已完成integration/renderer - 渲染器基类
定义渲染器接口和基础实现。
主要功能:
- 渲染器类型定义
- 通用渲染接口
- 实例管理
- 属性更新
核心接口:
type Renderer = (dom: HTMLElement, props: JsonObject) => RendererInstance;
interface RendererInstance {
app: any; // 应用实例
update: (newProps: JsonObject) => void; // 更新方法
}integration/renderer-react - React适配器
为React组件提供自动渲染和水合支持。
主要功能:
- React组件创建和挂载
- JSX运行时集成
- 属性传递和更新
- React根管理
使用方式:
import { createReactRenderer } from 'rsx-core/integration';
import App from './App.tsx';
const renderer = createReactRenderer(App);
// 在水合时使用
const instance = renderer(domElement, props);
// 更新组件
instance.update({ newProp: value });工作原理:
- 使用React 19的
createRootAPI - 通过JSX运行时渲染组件
- 支持属性动态更新
- 销毁时自动卸载
client - 客户端运行时API
提供在浏览器中使用的运行时API和响应式系统。
defineProps - 属性定义
在浏览器端定义组件属性。
const { data, loading, onUpdate } = defineProps<{
data: unknown[];
loading: boolean;
onUpdate: (data: unknown) => void;
}>();特点:
- TypeScript类型安全
- 仅在浏览器端运行
- 对象解构支持
- 默认值处理
defineState - 状态定义
定义组件响应式状态。
const { count, setText } = defineState({
count: 0,
text: ''
});defineActions - 行为定义
定义可调用的组件行为(事件处理器)。
const { onClick, onSubmit } = defineActions();effect / computed - 响应式API
定义副作用和计算属性。
effect(); // 监听状态变化执行副作用
computed(); // 创建计算属性
// 别名
$effect();
$computed();其他运行时函数
$nextTick(); // 在下一个事件循环执行
$forceUpdate(); // 强制重新渲染完整示例:
import { defineProps, defineState, defineActions, effect, computed } from 'rsx-core/client';
const props = defineProps<{ initialCount: number }>();
const { count, setCount } = defineState({ count: props.initialCount });
const { onClick } = defineActions();
// 计算属性
const doubled = computed(() => count * 2);
// 副作用
effect(() => {
console.log(`Count changed to ${count}`);
});
// 事件处理
onClick(() => {
setCount(count + 1);
});cli - 命令行工具
RSX框架的命令行工具,提供开发和构建能力。
dev - 开发服务器
启动开发服务器,支持热重载。
rsx dev [options]
选项:
--config <path> 配置文件路径 (默认: ./rsx.config.ts)
--port <port> 服务器端口 (默认: 4500)
--host <host> 服务器地址 (默认: localhost)
--mode <mode> 运行模式 (默认: development)功能:
- Vite开发服务器启动
- Cargo Rust后端进程管理
- RSX文件变化监听
- 增量编译和热更新
build - 生产构建
构建生产版本。
rsx build [options]
选项:
--config <path> 配置文件路径
--mode <mode> 构建模式 (默认: production)fmt - 代码格式化
格式化代码文件。
rsx fmt [options]
选项:
--dir <path> 格式化的目录
--files <files> 格式化的文件check - 代码检查
检查代码风格。
rsx check [options]
选项:
--dir <path> 检查的目录
--files <files> 检查的文件
--indent <spaces> 缩进空格数
--semicolon 在语句末尾使用分号⚙️ 配置
配置文件
在项目根目录创建 rsx.config.ts:
import { defineConfig } from 'rsx-core';
export default defineConfig({
root: process.cwd(),
pages: './src/pages',
public: './public',
renderer: ['react', 'vue', 'svelte'],
cache: './node_modules/.rsx',
output: './dist',
port: 4500,
host: 'localhost'
});配置选项
| 选项 | 类型 | 默认值 | 说明 |
| ---------- | ----------------- | -------------------------- | -------------- |
| root | string | process.cwd() | 项目根目录 |
| config | string | ./rsx.config.ts | 配置文件路径 |
| pages | string | ./src/pages | RSX页面目录 |
| public | string | boolean | ./public | 静态文件目录 |
| renderer | string[] | ['vue','react','svelte'] | 支持的渲染器 |
| cache | string | ./node_modules/.rsx | 缓存目录 |
| output | string | ./dist | 输出目录 |
| port | number | 4500 | 开发服务器端口 |
| host | string | localhost | 开发服务器地址 |
环境变量
支持通过环境变量覆盖配置:
RSX_PORT=3000 RSX_HOST=0.0.0.0 rsx dev🔌 客户端集成
React集成
创建React组件并在RSX中使用:
// components/Counter.tsx
import { defineProps, defineState } from 'rsx-core/client';
export function Counter() {
const props = defineProps<{ initialCount: number }>();
const { count, setCount } = defineState({ count: props.initialCount });
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
}<!-- pages/index.rsx -->
<script>
import Counter from '../components/Counter.tsx';
</script>
<template>
<div>
<h1>Welcome to RSX</h1>
<Counter client="react" initialCount="{{initialCount}}" />
</div>
</template>Vue集成
类似的方式支持Vue组件(支持规划中)。
Svelte集成
类似的方式支持Svelte组件(支持规划中)。
🏗️ 架构设计
编译流程
RSX文件
↓
Tree-sitter解析 (AST)
↓
分类 (页面/组件)
↓
Rust部分 → 后端代码
TypeScript部分 → 前端代码
Template部分 → Handlebars模板
Style部分 → SCSS/CSS
↓
生成缓存文件
↓
Vite处理
↓
JavaScript模块水合流程
浏览器加载HTML
↓
加载JavaScript包
↓
执行hydration()函数
↓
扫描data-rsx-component标记
↓
获取服务端props
↓
为每个组件创建渲染器
↓
挂载组件
↓
标记hydration=true开发服务器流程
执行rsx dev
↓
启动Vite开发服务器
↓
启动Cargo进程(Rust后端)
↓
监听RSX文件变化
↓
RSX文件更改 → 重启Cargo
↓
其他文件更改 → Vite热更新📁 项目结构
src/
├── cli/ # 命令行工具
│ ├── index.ts # CLI入口
│ ├── dev.ts # 开发命令
│ ├── build.ts # 构建命令
│ ├── fmt.ts # 格式化命令
│ └── check.ts # 检查命令
├── core/ # 核心编译器
│ ├── compiler.ts # RSX编译器
│ ├── vite.ts # Vite插件
│ ├── logger.ts # 日志系统
│ ├── types.ts # 类型定义
│ └── index.ts # 核心导出
├── client/ # 浏览器运行时
│ ├── index.ts # 客户端导出
│ ├── props.ts # 属性定义
│ ├── state.ts # 状态定义
│ ├── effect.ts # 响应式API
│ ├── component.ts # 组件定义
│ └── web-component.ts # Web Component
├── integration/ # 客户端集成
│ ├── index.ts # 集成导出
│ ├── provider.ts # 全局状态提供者
│ ├── hydration.ts # 水合运行时
│ ├── renderer.ts # 渲染器基类
│ └── renderer-react.ts # React适配器
├── config.ts # 配置管理
├── constants.ts # 常量定义
├── utils.ts # 工具函数
└── index.ts # 主入口📝 开发规范
TypeScript规范
- 使用单引号字符串
- 使用ES6模块化
- 使用async/await处理异步
- 使用try/catch处理异常
- 组件使用函数式组件
文件命名
- 工具/hook文件:kebab-case (
use-window-state.ts) - 组件文件:PascalCase (
Counter.tsx) - 类型定义:
*.ts或*.tsx
代码组织
// 导入
import { Component } from 'rsx-core';
// 类型定义
interface Props {}
// 组件实现
export function MyComponent(props: Props) {}🧪 测试
运行测试:
npm run test:cli编译器单元测试:
pnpm test🔄 常见操作
添加新页面
在 src/pages/ 目录创建 .rsx 文件:
---
async fn get_server_side_props(req: Request) -> Response {
Response::json!({ "title": "My Page" })
}
---
<script>
const { title } = defineProps<{ title: string }>()
</script>
<template>
<h1>{{ title }}</h1>
</template>
<style>
h1 { font-size: 2rem; }
</style>创建可复用组件
在 src/components/ 创建组件:
// src/components/Button.tsx
import { defineProps } from 'rsx-core/client';
export function Button() {
const { label, onClick } = defineProps<{
label: string;
onClick?: () => void;
}>();
return <button onClick={onClick}>{label}</button>;
}在模板中使用组件
<script>
import Button from './components/Button.tsx';
</script>
<template>
<button client="react" label="Click me" />
</template>🚀 性能优化
代码分割
配置自动按框架分割:
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: (id) => {
if (id.includes('react')) return 'react-vendor';
if (id.includes('vue')) return 'vue-vendor';
if (id.includes('svelte')) return 'svelte-vendor';
}
}
}
}
});缓存策略
- 利用
node_modules/.rsx缓存编译结果 - RSX文件基于
mtimeMs增量编译 - 支持增量构建和开发
📚 相关文档
🔗 相关模块
rsx-rust- Rust核心库example- 示例项目
📜 许可证
本项目采用MIT许可证 - 详见LICENSE文件。
RSX Node.js实现 - 构建高性能全栈Web应用
