使用 Unifiedjs 将 Markdown 转换为 HTML

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

我正在使用

unified()
remark-directive
remark-parse
将 Markdown 转换为 HTML,我可以成功转换大部分 Markdown,但下面的 Markdown 格式将被忽略。我知道锚标记的以下降价模式
[Anchor Link Text](https://test.com)
效果很好。有人遇到过这种模式吗?我正在寻找任何可以帮助解决此问题的
unified
插件,但没有任何运气。

:a[Anchor Link Text]{href='https://www.testurl.com/movies/news/the-url-to-test'}

html markdown remarkjs
1个回答
0
投票

语法看起来像通用指令提案

在 API 下的

remark-directive
文档中,它指出该插件解析语法树的指令(如
containerDirective
leafDirective
textDirective
等)。该插件不处理指令的实现/转换,开发人员需要实现自己的插件来处理指令。由于指令是通用的而不是标准化的,因此可能没有针对每个项目的独特实现的预制插件。

myRemarkPlugin
remark-directive
部分中的自定义插件
Use
示例可以方便地涵盖您的用例。

函数

myRemarkPlugin
创建一个与
:a
具有相同名称的标签以及来自
{}
的属性。在所需的情况下,将
:a
替换为 HTML 标签
a
,并且指令键/值
{href="#"}
是适合该实现的 HTML 标签属性。

它将把任何

:::
::
:
指令转换为同名的 HTML 标签,因此请根据您的要求调整逻辑。如果还有其他指令替换模式,则需要用自己的逻辑来处理。

Use
示例来自
remark-directive
GitHub:

// Register `hName`, `hProperties` types, used when turning markdown to HTML:
/// <reference types="mdast-util-to-hast" />
// Register directive nodes in mdast:
/// <reference types="mdast-util-directive" />

import {h} from 'hastscript'
import rehypeFormat from 'rehype-format'
import rehypeStringify from 'rehype-stringify'
import remarkDirective from 'remark-directive'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import {read} from 'to-vfile'
import {unified} from 'unified'
import {visit} from 'unist-util-visit'

const file = await unified()
  .use(remarkParse)
  .use(remarkDirective)
  .use(myRemarkPlugin) // Custom plugin defined below
  .use(remarkRehype)
  .use(rehypeFormat)
  .use(rehypeStringify)
  .process(await read('example.md'))

// Custom plugin
function myRemarkPlugin() {
  /**
   * @param {import('mdast').Root} tree
   *   Tree.
   * @returns {undefined}
   *   Nothing.
   */
  return function (tree) {
    visit(tree, function (node) {
      if (
        node.type === 'containerDirective' ||  // ':::' 
        node.type === 'leafDirective' || // '::' 
        node.type === 'textDirective' // ':' 
      ) {
        const data = node.data || (node.data = {})
        const hast = h(node.name, node.attributes || {})

        data.hName = hast.tagName
        data.hProperties = hast.properties
      }
    })
  }
}

使用自定义插件实现转变

:::main{#readme}

Lorem:br
ipsum.

::hr{.red}

A :i[lovely] language know as :abbr[HTML]{title="HyperText Markup Language"}.

:::

进入

<main id="readme">
  <p>Lorem<br>ipsum.</p>
  <hr class="red">
  <p>A <i>lovely</i> language know as <abbr title="HyperText Markup Language">HTML</abbr>.</p>
</main>

并且应该转变

:a[Anchor Link Text]{href='https://www.testurl.com/movies/news/the-url-to-test'}

进入

<a href="https://www.testurl.com/movies/news/the-url-to-test">Anchor Link Test</a>
© www.soinside.com 2019 - 2024. All rights reserved.