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

将AST转换为React组件时,非拉丁文本转Unicode转义序列问题

保留非拉丁文本在Babel生成JSX代码中的原格式

在使用Babel解析、修改AST并重新生成React组件代码时,西里尔字母等非拉丁文本会被自动转换为Unicode转义序列。例如尝试给按钮添加属性attrName="киррилица",期望生成的代码是:

<button attrName="киррилица">текст</button>

但实际生成的代码中,属性值被转义为Unicode序列:

<button attrName="\u043A\u0438\u0440\u0440\u0438\u043B\u0438\u0446\u0430">текст</button>

解决方案

要保留原非拉丁文本,需要调整两个关键点:

  • 给Babel Generator添加jsxEscapeMode: 'preserve'配置,禁用JSX属性值的自动转义
  • 手动设置字符串字面量的extra.raw字段,确保生成器使用原始文本而非转义序列

修改后的完整代码如下:

const generator = require('@babel/generator').default;
const { parse } = require('@babel/parser');
const traverse = require('@babel/traverse').default;


const code = `
import React from 'react';

export const Component = () => {
  return (
    <button>текст</button>
  );
};
`

const ast = parse(code, { sourceType: "module", plugins: ['jsx', 'typescript'] });

traverse(ast, {
  JSXOpeningElement(path) {
    const { attributes } = path.node || {};

    const newAttr = {
      type: 'JSXAttribute',
      name: {
        type: 'JSXIdentifier',
        name: 'attrName',
      },
      value: {
        type: 'StringLiteral',
        value: 'киррилица',
        // 添加extra.raw字段指定原始显示文本
        extra: {
          raw: '"киррилица"'
        }
      },
    }

    attributes.push(newAttr)
  },
}, { scope: {} });

// 添加jsxEscapeMode: 'preserve'配置
const options = { retainLines: true, comments: true, jsxEscapeMode: 'preserve' };
const output = generator(ast, options, code).code;

console.log('output code: ', output);

修改后的输出

运行上述代码后,将得到期望的结果:

output code:  
import React from 'react';

export const Component = () => {
  return (
    <button attrName="киррилица">текст</button>);

};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:58:14