diff --git a/packages/cli/src/api/parsers/babel.js b/packages/cli/src/api/parsers/babel.js index 3667c202..8060d995 100644 --- a/packages/cli/src/api/parsers/babel.js +++ b/packages/cli/src/api/parsers/babel.js @@ -73,7 +73,19 @@ function toStr(children, counter = 0) { } } else if (child.type === 'JSXText') { // Child is not a React element, append as-is - const chunk = child.value.trim().replace(/\s+/g, ' '); + let chunk = child.value; + + // Try to mimic how JSX is parsed in runtime React + const [startMatch] = /^[\s\n]*/.exec(child.value); + if (startMatch.includes('\n')) { + chunk = chunk.substring(startMatch.length); + } + + const [endMatch] = /[\s\n]*$/.exec(child.value); + if (endMatch.includes('\n')) { + chunk = chunk.substring(0, chunk.length - endMatch.length); + } + if (chunk) { result.push(chunk); } } else if ( child.type === 'JSXExpressionContainer' @@ -195,7 +207,7 @@ function babelExtractPhrases(HASHES, source, relativeFile, options) { if (!string && elem.name.name === 'T' && node.children && node.children.length) { const [result] = toStr(node.children); - string = result.join(' ').trim(); + string = result.join('').trim(); } if (!string) return; diff --git a/packages/react/src/components/T.jsx b/packages/react/src/components/T.jsx index 140f8244..bac7abd0 100644 --- a/packages/react/src/components/T.jsx +++ b/packages/react/src/components/T.jsx @@ -49,7 +49,7 @@ export default function T({ _str, children, ...props }) { if (!children) { return t(_str, props); } const [templateArray, propsContainer] = toStr(children); - const templateString = templateArray.join(' ').trim(); + const templateString = templateArray.join('').trim(); const translation = t(templateString, props); const result = toElement(translation, propsContainer); diff --git a/packages/react/src/utils/toStr.js b/packages/react/src/utils/toStr.js index 7da07fd9..861f827d 100644 --- a/packages/react/src/utils/toStr.js +++ b/packages/react/src/utils/toStr.js @@ -64,8 +64,7 @@ export function toStr(children, counter = 0) { // Child is not a React element, append as-is /* eslint-disable no-lonely-if */ if (typeof child === 'string' || child instanceof String) { - const chunk = child.trim().replace(/\s+/g, ' '); - if (chunk) { result.push(chunk); } + if (child) { result.push(child); } } else { result.push(child); }