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

使用swc将AST还原为代码时遇JSXElement错误的解决方法

解决swc.printSync无法还原JSX片段AST的问题

问题原因

swc的printSync方法要求传入的AST根节点必须是Module或Script类型,而直接解析孤立的JSX片段时,得到的AST根节点是JSXElement,不符合方法的输入要求,因此触发报错。

解决方法

方法一:将JSX片段包裹为完整模块后解析

把孤立的JSX片段嵌入到完整的模块结构中(比如导出一个返回该JSX的函数),让swc解析出顶层的Module节点,再进行打印:

const swc = require('@swc/core');

// 你的原始JSX片段
const jsxSnippet = `<>
    <Divider orientation="left">{resultLinkTitle}</Divider>
    <Intension />
    <Form form={form} name="auditForm" ref={auditFormRef}>
      <Form.Item label="files">
        <Button type="link" onClick={() => handleDownLoadFile(aduitInfo?.fileUrl)}>
          download
        </Button>
      </Form.Item>
    </Form>
  </>`;

// 包裹成完整的ES模块
const wrappedCode = `export default () => { return ${jsxSnippet}; }`;

// 解析时开启JSX支持
const ast = swc.parse(wrappedCode, {
  syntax: 'typescript', // 若使用JS则改为'ecmascript'
  jsx: true,
});

// 还原代码
const { code } = swc.printSync(ast);
console.log(code);

方法二:手动构造包含JSXElement的Module节点

如果不想修改原始代码字符串,可以手动创建Module节点,将解析得到的JSXElement作为表达式嵌入到ExpressionStatement中:

const swc = require('@swc/core');

const jsxSnippet = `<>...</>`; // 你的原始JSX片段

// 解析JSX片段(此时根节点是JSXElement)
const jsxAst = swc.parse(jsxSnippet, {
  syntax: 'typescript',
  jsx: true,
});

// 构造符合要求的Module节点
const wrappedAst = {
  type: 'Module',
  body: [
    {
      type: 'ExpressionStatement',
      expression: jsxAst,
    },
  ],
  span: jsxAst.span,
};

// 打印还原代码
const { code } = swc.printSync(wrappedAst);
console.log(code);

关键注意点

  • 解析时必须配置jsx: true,否则swc无法识别JSX语法。
  • 根据代码环境选择syntax参数:TypeScript用'typescript',普通JS用'ecmascript'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:17:47