VuReact 于 7 月 1 日正式发布 v1.10.0 版本。本次更新新增了 Vue 3 withDefaults 宏的编译支持#63,同时修复了使用 unplugin-auto-import 等免 import 插件时的 API 识别问题#62,并对编译流程提示进行了优化。
新增 withDefaults 编译支持
withDefaults 是 Vue 3 <script setup> 中用于为 defineProps 声明的 prop 提供编译时默认值的工具函数。VuReact 将其编译为 useMemo + 空值合并运算符 ?? 的组合,在组件初始化时合并传入的 props 与默认值,生成一个包含完整默认值的只读 props 对象。
代码示例:
Vue 源码(使用 withDefaults):
<script setup lang="ts">
interface Props {
msg?: string;
count?: number;
labels: string[];
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
count: 42,
labels: () => ['one', 'two'],
});
</script>
<template>
<div>{{ props.msg }} {{ props.count }}</div>
<ul>
<li v-for="value in props.labels" :key="value">{{ value }}</li>
</ul>
</template>
VuReact 编译后的 React 产物:
import { useMemo, memo } from 'react';
interface Props {
msg?: string;
count?: number;
labels: string[];
}
export type ICompProps = Props;
const Input = memo((vrProps: ICompProps) => {
const props = useMemo<Readonly<Props>>(() => ({
...vrProps,
msg: vrProps.msg ?? 'hello',
count: vrProps.count ?? 42,
labels: vrProps.labels ?? ['one', 'two'],
}), [vrProps]);
return (
<>
<div>{props.msg}{props.count}</div>
<ul>
{props.labels.map(value => <li key={value}>{value}</li>)}
</ul>
</>
);
});
export default Input;
从示例可以看到:Vue 的 withDefaults 被编译为 useMemo + 空值合并运算符 ?? 的组合。基本类型默认值直接作为 ?? 右侧的字面量值;数组、对象等引用类型默认值则遵循 Vue 的工厂函数约定,保证每次渲染生成独立的引用实例,避免引用共享导致的副作用污染。
本次更新其他内容:
- Bug 修复:修复使用
unplugin-auto-import 等免 import 插件时,Vue API(如 ref、computed、onMounted 等)因内部 adapter 缺少 binding 无法识别,导致跳过转换的问题
- 编译流程优化:将编译阶段提示从单一的
Compiling Vue to React... 细分为 Compiling components/scripts/styles...,便于开发者更清晰地了解当前编译进度
- 新增
withDefaults 转换的单元测试覆盖
关于 VuReact
VuReact 是专为 Vue 迁移 React 设计的智能编译器,采用语义级编译路线,用于将 Vue 3 单文件组件・脚本・样式完整转为纯 React(非运行时桥接)代码并输出工程化产物,覆盖 <script setup> 核心全特性,支持渐进式迁移与 Vue+React 混合开发。
目前已完成 defineProps、defineEmits、defineExpose、defineModel、withDefaults 等核心宏的语义映射,以及 ref、computed、watch、scoped style 等 Vue 特性的完整适配。
详情可查阅: