如何在 TSX TypeScript 中保留 JSX 标签内的换行符?

问题描述 投票:0回答:1

我想使用 TSX 进行 Markdown 渲染,问题是 - TypeScript TSX 编译器剥离换行符并且它破坏了 markdown。

下面的示例将输出文本为

Some text. - list item a - list item b
,并删除换行符,playground

有可能以某种方式阻止它吗?

const React = {
  createElement(tag: any, attrs: any, ...children: any[]): any {
    return console.log(JSON.stringify({ tag, attrs, children }))
  }
};

<markdown>
  Some text.

  - list item a
  - list item b
</markdown>

附注

也许可以使用 TypeScript 编译器选项(例如 Transformers 等)来实现?比如 - 拦截源加载并将 JSX 标签中文本中的

\n
替换为
__NL__\n
,因此,在 Markdown 渲染阶段可以通过用
__NL__
替换
\n
来恢复换行符吗?

或者也许可以使用一些自定义 API 为特定引擎 bun.js 做到这一点?

typescript tsx bun mdxjs
1个回答
0
投票

我不完全确定这就是你想要的,但让我们讨论一下......

我相信你所追求的可以通过模板文字和CSS

white-space: pre-wrap
来实现。

这似乎不是 TypeScript 编译器的问题,更多的是 HTML 基于 压缩算法 压缩空白。
请注意,新行通常会被压缩:

Table for White-space

直接来自MDN

的表格

解决方案:

white-space: pre-wrap

import React from 'react';

export default function App() {

  const markdown = `  Some text.

  - list item a
  - list item b
  - this is a really long piece of text that should wrap when given the chance to do so. You may need to adjust the size of the window to test this theory out!
  `
  return (
    <div className='App'>
      {markdown}
    </div>
  );
}
body {
  background: white;
}

.App {
  color: black;
  white-space: pre-wrap;
}

游乐场链接

var text = `  Some text.

  - list item a
  - list item b
  - this is a really long piece of text that should wrap when given the chance to do so. You may need to adjust the size of the window to test this theory out!
  `;

document.getElementById("element").innerText = text
#element {
  white-space: pre-wrap;
}
<div id="element"></div>

或者

您可以使用诸如React-Markdown之类的包,因为它可能更容易实现,请参阅他们的演示
还存在其他软件包,这只是可以使用的许多软件包的一个示例。

import React from 'react'
import {createRoot} from 'react-dom/client'
import Markdown from 'react-markdown'

const markdown = '# Hi, *Pluto*!'

createRoot(document.body).render(<Markdown>{markdown}</Markdown>)
© www.soinside.com 2019 - 2024. All rights reserved.