React Web应用本地化:编写runCommands脚本实现翻译自动化
React本地化自动处理快捷键配置方案
要实现选中硬编码文本后一键包裹t()函数并同步添加到english.json,仅靠VS Code内置的runCommands无法完成复杂的文本转换和文件写入操作,需要结合Multi Command扩展来组合多步命令。以下是完整配置步骤:
1. 安装Multi Command扩展
在VS Code扩展市场搜索并安装「Multi Command」,它允许我们将多个命令组合成一个自定义命令。
2. 配置自定义命令(settings.json)
打开用户或工作区的settings.json,添加以下配置(根据操作系统调整终端命令):
Mac/Linux版本
"multiCommand.commands": [ { "command": "multiCommand.addTranslation", "sequence": [ // 1. 复制选中的硬编码文本到剪贴板 "editor.action.clipboardCopyAction", // 2. 将原文保存到临时文件(避免后续覆盖剪贴板) { "command": "workbench.action.terminal.sendSequence", "args": { "text": "pbpaste > /tmp/translation_text\n" } }, // 3. 将原文转换为符合规范的翻译key(小写+下划线)并复制到剪贴板 { "command": "workbench.action.terminal.sendSequence", "args": { "text": "echo -n \"${selectedText}\" | sed 's/[^a-zA-Z0-9]/_/g' | tr '[:upper:]' '[:lower:]' | pbcopy\n" } }, // 4. 将选中的原文替换为{t('key')}格式 { "command": "editor.action.replaceSelection", "args": { "text": "{t('')}" } }, "cursorLeft", "editor.action.clipboardPasteAction", // 5. 打开项目的english.json文件(根据你的路径调整) { "command": "workbench.action.files.openFile", "args": { "file": "${workspaceFolder}/src/locales/english.json" } }, // 6. 定位到文件末尾并插入新的翻译键值对 "cursorBottom", "editor.action.insertLineAfter", { "command": "editor.action.replaceSelection", "args": { "text": " \"${clipboard}\": \"" } }, // 7. 粘贴之前保存的原文作为value { "command": "workbench.action.terminal.sendSequence", "args": { "text": "cat /tmp/translation_text | pbcopy\n" } }, "editor.action.clipboardPasteAction", { "command": "editor.action.replaceSelection", "args": { "text": "\"," } }, // 8. 格式化JSON文件确保语法正确 "editor.action.formatDocument" ] } ]
Windows版本(PowerShell)
将上述配置中的终端命令替换为以下内容:
// 保存原文到临时文件 { "command": "workbench.action.terminal.sendSequence", "args": { "text": "Get-Clipboard | Out-File -FilePath $env:TEMP\\translation_text -Encoding utf8\n" } }, // 生成翻译key并复制到剪贴板 { "command": "workbench.action.terminal.sendSequence", "args": { "text": "Get-Clipboard | ForEach-Object { $_ -replace '[^a-zA-Z0-9]', '_' } | ForEach-Object { $_.ToLower() } | Set-Clipboard\n" } }, // 读取原文并复制到剪贴板 { "command": "workbench.action.terminal.sendSequence", "args": { "text": "Get-Content $env:TEMP\\translation_text | Set-Clipboard\n" } }
3. 绑定快捷键(keybindings.json)
打开keybindings.json,添加以下配置绑定快捷键:
{ "key": "alt+shift+t", "command": "multiCommand.addTranslation", "when": "editorTextFocus && editorHasSelection" }
使用说明
- 选中React代码中的硬编码字符串(例如
"Welcome to our app") - 按下
Alt+Shift+T快捷键 - 选中的文本会自动替换为
t('welcome_to_our_app')格式,同时english.json文件会自动添加对应的键值对:"welcome_to_our_app": "Welcome to our app"
内容的提问来源于stack exchange,提问作者StephenL
相关产品推荐
相关产品推荐

