You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从React组件获取JSX/TSX源码?实现示例代码复用展示

实现「渲染示例+TSX源码」配对展示的方案

要实现不重复编写代码的「组件渲染+源码展示」,核心问题是运行时无法通过ref获取TSX源码——因为TSX在构建阶段已经被编译为React.createElement调用,浏览器中只存在渲染后的DOM结构,没有原始源码信息。必须在构建或编译阶段提前提取源码,再注入到页面中。

一、自定义构建配置提取源码

通过构建工具(Webpack/Vite)的插件/loader,在编译时将TSX文件的源码作为额外导出项,这样就能在组件中同时导入组件本身和对应的源码。

Vite 配置示例

在vite.config.ts中添加自定义插件,自动给TSX文件追加源码导出:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [
    react(),
    {
      name: 'extract-tsx-source',
      transform(code, id) {
        // 只处理项目内的TSX文件
        if (id.endsWith('.tsx') && !id.includes('node_modules')) {
          // 将源码转为字符串导出
          const sourceCode = JSON.stringify(code);
          return `${code}\nexport const sourceCode = ${sourceCode};`;
        }
        return code;
      }
    }
  ]
});

使用方式

导入组件时同时获取源码,配合语法高亮组件展示:

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
import MyComponent, { sourceCode } from './MyComponent.tsx';

export default function Demo() {
  return (
    <div className="demo-wrap">
      <div className="demo-preview">
        <h4>组件渲染效果</h4>
        <MyComponent />
      </div>
      <div className="demo-source">
        <h4>TSX源码</h4>
        <SyntaxHighlighter language="tsx" style={vscDarkPlus}>
          {sourceCode}
        </SyntaxHighlighter>
      </div>
    </div>
  );
}

二、使用成熟库简化实现

直接使用封装好的组件库,无需自己配置构建工具,常见的有:

@uiw/react-code-preview

专门用于React组件的演示与源码展示,内置语法高亮,支持实时编辑预览:

import CodePreview from '@uiw/react-code-preview';
import MyComponent from './MyComponent.tsx';
// 通过Vite的?raw后缀直接导入源码字符串
import myComponentSource from './MyComponent.tsx?raw';

export default function DemoPage() {
  return (
    <CodePreview
      code={myComponentSource}
      language="tsx"
      showCode={true}
    >
      <MyComponent />
    </CodePreview>
  );
}

react-live

支持实时编辑并预览组件效果,适合需要交互演示的场景:

import { LiveProvider, LiveEditor, LivePreview } from 'react-live';
import myComponentSource from './MyComponent.tsx?raw';

export default function LiveDemo() {
  return (
    <LiveProvider code={myComponentSource} language="tsx">
      <LivePreview />
      <LiveEditor />
    </LiveProvider>
  );
}

关键注意点

  • 不要尝试在运行时通过DOM或ref获取源码:TSX编译后已无源码信息,这种方法只能拿到渲染后的HTML结构,无法得到原始TSX代码。
  • 语法高亮依赖第三方库:如react-syntax-highlighter、prismjs等,需配合使用才能让源码有良好的展示效果。

内容的提问来源于stack exchange,提问作者Okarin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 21:34:55