|
| 1 | +import * as parser from '@babel/parser'; |
| 2 | +import type { NodePath } from '@babel/traverse'; |
| 3 | +import _traverse from '@babel/traverse'; |
| 4 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 5 | +const traverse = (_traverse as any).default; |
| 6 | +import _generate from '@babel/generator'; |
| 7 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 8 | +const generate = (_generate as any).default; |
| 9 | +import * as t from '@babel/types'; |
| 10 | + |
| 11 | +const KOREAN_REGEX = /[가-힣]/; |
| 12 | + |
| 13 | +/** |
| 14 | + * 코드 문자열을 파싱하여 AST로 변환 |
| 15 | + */ |
| 16 | +export function parseCode(code: string) { |
| 17 | + return parser.parse(code, { |
| 18 | + sourceType: 'module', |
| 19 | + plugins: ['jsx', 'typescript'], |
| 20 | + }); |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * 리액트 컴포넌트 함수인지 판별 |
| 25 | + */ |
| 26 | +function isReactComponentFunction(path: NodePath): boolean { |
| 27 | + // 함수 선언문 |
| 28 | + if (path.isFunctionDeclaration()) { |
| 29 | + return path.node.id?.name?.[0] === path.node.id?.name?.[0]?.toUpperCase(); |
| 30 | + } |
| 31 | + |
| 32 | + // 화살표 함수 표현식 또는 함수 표현식 |
| 33 | + if (path.isArrowFunctionExpression() || path.isFunctionExpression()) { |
| 34 | + const parent = path.parentPath; |
| 35 | + |
| 36 | + // 변수 선언문 |
| 37 | + if (parent?.isVariableDeclarator()) { |
| 38 | + const varName = (parent.node.id as t.Identifier)?.name; |
| 39 | + return /^[A-Z]/.test(varName); |
| 40 | + } |
| 41 | + |
| 42 | + // 합성 컴포넌트 |
| 43 | + if (parent?.isAssignmentExpression()) { |
| 44 | + const left = parent.get('left'); |
| 45 | + if (left.isMemberExpression()) { |
| 46 | + const property = left.get('property'); |
| 47 | + if (property.isIdentifier()) { |
| 48 | + return /^[A-Z]/.test(property.node.name); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return false; |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * AST에서 한글 문자열 탐색 및 변환 |
| 59 | + */ |
| 60 | +export function transformAST(ast: t.File) { |
| 61 | + const koreanKeys = new Set<string>(); |
| 62 | + const componentsToModify = new Set<NodePath>(); |
| 63 | + let hasUseTranslationImport = false; |
| 64 | + const simpleStringsToTransform: NodePath<t.StringLiteral | t.JSXText>[] = []; |
| 65 | + const templateLiteralsToTransform: { |
| 66 | + path: NodePath<t.TemplateLiteral>; |
| 67 | + i18nKey: string; |
| 68 | + objectProperties: t.ObjectProperty[]; |
| 69 | + }[] = []; |
| 70 | + |
| 71 | + // 1️. 한글 문자열 탐색 및 변환 대상 수집 |
| 72 | + traverse(ast, { |
| 73 | + JSXText(path) { |
| 74 | + const value = path.node.value.trim(); |
| 75 | + if (value && KOREAN_REGEX.test(value)) { |
| 76 | + const component = path.findParent((p) => isReactComponentFunction(p)); |
| 77 | + if (component) { |
| 78 | + const parentT = path.findParent( |
| 79 | + (p) => |
| 80 | + p.isCallExpression() && |
| 81 | + p.get('callee').isIdentifier({ name: 't' }), |
| 82 | + ); |
| 83 | + if (parentT) return; |
| 84 | + |
| 85 | + simpleStringsToTransform.push(path); |
| 86 | + koreanKeys.add(value); |
| 87 | + componentsToModify.add(component); |
| 88 | + } |
| 89 | + } |
| 90 | + }, |
| 91 | + StringLiteral(path) { |
| 92 | + const value = path.node.value.trim(); |
| 93 | + if ( |
| 94 | + value && |
| 95 | + KOREAN_REGEX.test(value) && |
| 96 | + path.parent.type !== 'ImportDeclaration' && |
| 97 | + path.parent.type !== 'ExportNamedDeclaration' && |
| 98 | + !( |
| 99 | + path.parent.type === 'ObjectProperty' && path.parent.key === path.node |
| 100 | + ) |
| 101 | + ) { |
| 102 | + const component = path.findParent((p) => isReactComponentFunction(p)); |
| 103 | + if (component) { |
| 104 | + const parentT = path.findParent( |
| 105 | + (p) => |
| 106 | + p.isCallExpression() && |
| 107 | + p.get('callee').isIdentifier({ name: 't' }), |
| 108 | + ); |
| 109 | + if (parentT) return; |
| 110 | + |
| 111 | + simpleStringsToTransform.push(path); |
| 112 | + koreanKeys.add(value); |
| 113 | + componentsToModify.add(component); |
| 114 | + } |
| 115 | + } |
| 116 | + }, |
| 117 | + TemplateLiteral(path) { |
| 118 | + const { quasis, expressions } = path.node; |
| 119 | + const hasKorean = quasis.some((q) => KOREAN_REGEX.test(q.value.raw)); |
| 120 | + if (!hasKorean) return; |
| 121 | + |
| 122 | + if ( |
| 123 | + path.parent.type === 'CallExpression' && |
| 124 | + t.isIdentifier(path.parent.callee) && |
| 125 | + path.parent.callee.name === 't' |
| 126 | + ) { |
| 127 | + return; |
| 128 | + } |
| 129 | + |
| 130 | + const component = path.findParent((p) => isReactComponentFunction(p)); |
| 131 | + if (!component) return; |
| 132 | + |
| 133 | + let i18nKey = ''; |
| 134 | + const objectProperties: t.ObjectProperty[] = []; |
| 135 | + |
| 136 | + for (let i = 0; i < quasis.length; i++) { |
| 137 | + i18nKey += quasis[i].value.raw; |
| 138 | + if (i < expressions.length) { |
| 139 | + const expr = expressions[i]; |
| 140 | + let placeholderName: string; |
| 141 | + |
| 142 | + if (t.isIdentifier(expr)) { |
| 143 | + placeholderName = expr.name; |
| 144 | + } else if ( |
| 145 | + t.isMemberExpression(expr) && |
| 146 | + t.isIdentifier(expr.property) |
| 147 | + ) { |
| 148 | + placeholderName = expr.property.name; |
| 149 | + } else { |
| 150 | + placeholderName = `val${i}`; |
| 151 | + } |
| 152 | + |
| 153 | + let finalName = placeholderName; |
| 154 | + let count = 1; |
| 155 | + while ( |
| 156 | + objectProperties.some( |
| 157 | + (p) => t.isIdentifier(p.key) && p.key.name === finalName, |
| 158 | + ) |
| 159 | + ) { |
| 160 | + finalName = `${placeholderName}${count++}`; |
| 161 | + } |
| 162 | + |
| 163 | + i18nKey += `{{${finalName}}}`; |
| 164 | + objectProperties.push( |
| 165 | + t.objectProperty( |
| 166 | + t.identifier(finalName), |
| 167 | + expr, |
| 168 | + false, |
| 169 | + t.isIdentifier(expr) && finalName === expr.name, |
| 170 | + ), |
| 171 | + ); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + koreanKeys.add(i18nKey); |
| 176 | + componentsToModify.add(component); |
| 177 | + templateLiteralsToTransform.push({ path, i18nKey, objectProperties }); |
| 178 | + }, |
| 179 | + ImportDeclaration(path) { |
| 180 | + if (path.node.source.value === 'react-i18next') { |
| 181 | + hasUseTranslationImport = true; |
| 182 | + } |
| 183 | + }, |
| 184 | + }); |
| 185 | + |
| 186 | + // 2️. useTranslation import 추가 |
| 187 | + if (koreanKeys.size > 0 && !hasUseTranslationImport) { |
| 188 | + const importDecl = t.importDeclaration( |
| 189 | + [ |
| 190 | + t.importSpecifier( |
| 191 | + t.identifier('useTranslation'), |
| 192 | + t.identifier('useTranslation'), |
| 193 | + ), |
| 194 | + ], |
| 195 | + t.stringLiteral('react-i18next'), |
| 196 | + ); |
| 197 | + ast.program.body.unshift(importDecl); |
| 198 | + } |
| 199 | + |
| 200 | + // 3️. 각 컴포넌트에 const { t } = useTranslation() 추가 |
| 201 | + componentsToModify.forEach((componentPath) => { |
| 202 | + const bodyPath = componentPath.get('body'); |
| 203 | + if (Array.isArray(bodyPath) || !bodyPath.isBlockStatement()) return; |
| 204 | + |
| 205 | + let hasHook = false; |
| 206 | + bodyPath.get('body').forEach((stmt) => { |
| 207 | + if (stmt.isVariableDeclaration()) { |
| 208 | + const declaration = stmt.node.declarations[0]; |
| 209 | + if ( |
| 210 | + declaration?.init?.type === 'CallExpression' && |
| 211 | + t.isIdentifier(declaration.init.callee) && |
| 212 | + declaration.init.callee.name === 'useTranslation' |
| 213 | + ) { |
| 214 | + hasHook = true; |
| 215 | + } |
| 216 | + } |
| 217 | + }); |
| 218 | + |
| 219 | + if (!hasHook) { |
| 220 | + const hookDecl = t.variableDeclaration('const', [ |
| 221 | + t.variableDeclarator( |
| 222 | + t.objectPattern([ |
| 223 | + t.objectProperty(t.identifier('t'), t.identifier('t'), false, true), |
| 224 | + ]), |
| 225 | + t.callExpression(t.identifier('useTranslation'), []), |
| 226 | + ), |
| 227 | + ]); |
| 228 | + bodyPath.unshiftContainer('body', hookDecl); |
| 229 | + } |
| 230 | + }); |
| 231 | + |
| 232 | + // 4️. 템플릿 리터럴 변환 |
| 233 | + templateLiteralsToTransform.forEach(({ path, i18nKey, objectProperties }) => { |
| 234 | + const keyLiteral = t.stringLiteral(i18nKey); |
| 235 | + if (objectProperties.length > 0) { |
| 236 | + const interpolationObject = t.objectExpression(objectProperties); |
| 237 | + const tCall = t.callExpression(t.identifier('t'), [ |
| 238 | + keyLiteral, |
| 239 | + interpolationObject, |
| 240 | + ]); |
| 241 | + path.replaceWith(tCall); |
| 242 | + } else { |
| 243 | + const tCall = t.callExpression(t.identifier('t'), [keyLiteral]); |
| 244 | + path.replaceWith(tCall); |
| 245 | + } |
| 246 | + }); |
| 247 | + |
| 248 | + // 5️. 컴포넌트 내부 한글 텍스트 t()로 감싸기 |
| 249 | + simpleStringsToTransform.forEach((path) => { |
| 250 | + const value = |
| 251 | + path.node.type === 'JSXText' |
| 252 | + ? path.node.value.trim() |
| 253 | + : (path.node as t.StringLiteral).value; |
| 254 | + |
| 255 | + const tCall = t.callExpression(t.identifier('t'), [t.stringLiteral(value)]); |
| 256 | + |
| 257 | + if (path.isJSXText()) { |
| 258 | + path.replaceWith(t.jsxExpressionContainer(tCall)); |
| 259 | + } else if (path.isStringLiteral()) { |
| 260 | + if (path.parent.type === 'JSXAttribute') { |
| 261 | + path.replaceWith(t.jsxExpressionContainer(tCall)); |
| 262 | + } else { |
| 263 | + path.replaceWith(tCall); |
| 264 | + } |
| 265 | + } |
| 266 | + }); |
| 267 | + |
| 268 | + return koreanKeys; |
| 269 | +} |
| 270 | + |
| 271 | +/** |
| 272 | + * AST를 코드 문자열로 다시 변환 |
| 273 | + */ |
| 274 | +export function generateCode(ast: t.File) { |
| 275 | + const { code } = generate(ast, { |
| 276 | + retainLines: true, |
| 277 | + jsescOption: { minimal: true }, |
| 278 | + }); |
| 279 | + return code; |
| 280 | +} |
0 commit comments