diff --git a/packages/uni-app-uts/__tests__/transforms/transformText.spec.ts b/packages/uni-app-uts/__tests__/transforms/transformText.spec.ts index adefa5473b9d541a6452484a7baf17b3cf1574f0..c26bd3813cf6d4c6fee05879cc6259beb4e3c7b7 100644 --- a/packages/uni-app-uts/__tests__/transforms/transformText.spec.ts +++ b/packages/uni-app-uts/__tests__/transforms/transformText.spec.ts @@ -30,6 +30,26 @@ describe('compiler: transform text', () => { ]), createElementVNode("text", null, toDisplayString(_ctx.eee) + "fff", 1 /* TEXT */), createElementVNode("text", null, toDisplayString(_ctx.ggg), 1 /* TEXT */) +])` + ) + }) + test('\n', () => { + assert( + ` + \\\\\n 换行 + \\\\n 换行 + \\\n 换行 + \\n 换行 + \n 换行 + \n 换行 \\n 换行 \\\n 换行 \\\\n 换行 \\\\\n 换行 +`, + `createElementVNode(\"view\", null, [ + createElementVNode(\"text\", null, \"\\\\\\\\ 换行\"), + createElementVNode(\"text\", null, \"\\\\n 换行\"), + createElementVNode(\"text\", null, \"\\\\ 换行\"), + createElementVNode(\"text\", null, \"\\n 换行\"), + createElementVNode(\"text\", null, \" 换行\"), + createElementVNode(\"text\", null, \" 换行 \\n 换行 \\\\ 换行 \\\\\\n 换行 \\\\\\\\ 换行\") ])` ) }) diff --git a/packages/uni-app-uts/src/plugins/uvue/compiler/transforms/transformText.ts b/packages/uni-app-uts/src/plugins/uvue/compiler/transforms/transformText.ts index 4ffdc67e38481de06a2438912a9dd1fbda76e648..8dd760cd987362e1cc8d2274e6a132d5a6e14ae2 100644 --- a/packages/uni-app-uts/src/plugins/uvue/compiler/transforms/transformText.ts +++ b/packages/uni-app-uts/src/plugins/uvue/compiler/transforms/transformText.ts @@ -84,16 +84,13 @@ function parseText(node: ElementNode) { let firstTextChild for (let i = 0; i < node.children.length; i++) { const child = node.children[i] - if (isText(child) && typeof (child as TextNode).content === 'string') { + const content = (child as TextNode).content + if (isText(child) && typeof content === 'string') { if (!firstTextChild) { firstTextChild = child - ;(firstTextChild as TextNode).content = ( - firstTextChild as TextNode - ).content.replace(/\\n/g, '\n') + ;(firstTextChild as TextNode).content = translateObliqueLine(content) } else { - ;(firstTextChild as TextNode).content += ( - child as TextNode - ).content.replace(/\\n/g, '\n') + ;(firstTextChild as TextNode).content += translateObliqueLine(content) node.children.splice(i, 1) i-- } @@ -123,3 +120,17 @@ function createText( loc: node.loc, } } + +function translateObliqueLine(content: string): string { + const strFragments = content.split('\\n') + return strFragments + .map((str, index) => { + if (index === strFragments.length - 1) return str + str += '\\n' + if (!(str.split('\\').length % 2)) { + str = str.replaceAll(/\\n/g, '\n') + } + return str.replaceAll(/\\\\/g, '\\') + }) + .join('') +}