VuReact 1.10.0 发布:新增 withDefaults 编译支持,修复 unplugin-auto-import 兼容问题

更新速览

VuReact 于 7 月 1 日正式发布 v1.10.0 版本。本次更新新增了 Vue 3 withDefaults 宏的编译支持,同时修复了使用 unplugin-auto-import 等免 import 插件时的 API 识别问题,并对编译流程提示进行了优化。

新增 withDefaults 编译支持

withDefaults 是 Vue 3 <script setup> 中用于为 defineProps 声明的 prop 提供编译时默认值的工具函数。VuReact 将其编译为 useMemo + 空值合并运算符 ?? 的组合,在组件初始化时合并传入的 props 与默认值,生成一个包含完整默认值的只读 props 对象。

Vue 源码(使用 withDefaults):

html 复制代码
<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 产物:

ts 复制代码
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;

编译逻辑解析:

处理方式 说明
基本类型默认值 直接作为 ?? 右侧的字面量值,仅在父组件未传递该 prop(即 undefined)时生效
引用类型默认值 遵循 Vue 的工厂函数约定,保证每次渲染生成独立的引用实例,避免引用共享导致的副作用污染
类型保留 Props 接口原样保留,不会因默认值而改变类型的可选/必填约束
只读保证 useMemo<Readonly<Props>> 确保返回的 props 对象是只读的,与 Vue 行为一致

本次更新其他内容

类型 说明
Bug 修复 修复使用 unplugin-auto-import 等免 import 插件时,Vue API(如 refcomputedonMounted 等)因内部 adapter 缺少 binding 无法识别,导致跳过转换的问题 Issue #62
编译流程优化 将编译阶段提示从单一的 Compiling Vue to React... 细分为 Compiling components/scripts/styles...,便于开发者更清晰了解当前编译进度
测试覆盖 新增 withDefaults 转换的单元测试覆盖

关于 VuReact

VuReact 是专为 Vue 迁移 React 设计的智能编译器。它用于将 Vue 3 单文件组件・脚本・样式完整转为纯 React(非运行时桥接)代码并输出工程化产物,覆盖 <script setup> 核心全特性,支持渐进式迁移与 Vue+React 混合开发。。

目前已完成适配的 Vue 特性:

  • 核心宏:definePropsdefineEmitsdefineExposedefineModelwithDefaults
  • 响应式 API:refcomputedwatchwatchEffect
  • 生命周期:onMountedonUnmounted
  • 样式:scoped style、CSS Modules 等
  • 模板语法:v-ifv-forv-model、插槽等

相关链接

写在最后

本次 withDefaults 编译支持的落地,配合之前版本已支持的 defineModel,标志着 VuReact 对 Vue 3 <script setup> 核心编译器宏的覆盖度已接近完成。如果你正在经历或即将经历 Vue → React 的迁移,欢迎在评论区分享你的场景和经验。

扩展阅读: