gpt4 book ai didi

gatsby - 配置 gatsby-transformer-remark 添加默认类

转载 作者:行者123 更新时间:2023-12-03 18:40:52 24 4
gpt4 key购买 nike

我正在使用带有插件的 gatsby gatsby-source-filesystemgatsby-transformer-remark将 markdown 文件显示为页面,如 official docs 中所述.

它工作得很好,但我正在寻找一种方法来向所有从 Markdown 转换的元素添加默认类。

假设我想要每个 <h1>具有 title 类的元素, 和 <h2>具有 subtitle 类的元素默认情况下。

我设法用 gatsby-remark-attr 做这样的事情,但这样我只能在 Markdown 文件中以编程方式添加类。它看起来像这样:

# My markdown heading
{.title}

## Subtitle
{.subtitle}

转换为

<h1 class="title">My markdown heading</h1>
<h2 class="subtitle">Subtitle</h2>

我正在寻找一种方法来为每个元素定义一次默认类并自动应用它们,而不必在 Markdown 文件中指定它们。

最佳答案

TL,博士:使用 gatsby-remark-default-html-attrs

Gatsby 的 gatsby-transformer-remark使用 mdast-util-to-hast 将 markdown 节点转换为 html 节点,然后将其字符串化为原始 HTML。如果markdown节点有data.hProperties对象,它将被转换为 html 属性。

假设您要添加类名 foo给所有人 h1节点。你需要:

  • 找到最终会转化为 h1 的 markdown 节点html 元素
  • 将 className 添加到其 data.hProperties

  • 0. 设置

    首先需要一个自定义插件来修改 transformer-remark的markdown节点.值得庆幸的是,使用 gatsby 创建本地插件很简单:

    # Create a `plugins` folder at your root
    mkdir plugins
    mkdir plugins/remark-default-class-name
    cd plugins/remark-default-class-name
    npm init -y
    touch index.js

    你现在会得到这个结构:
    root
    |--src
    |--gatsby-config.js
    `--plugins
    `--remark-default-class-name
    |--package.json
    `--index.js

    然后将新的本地插件添加到 gatsby-config.js :

    // gatsby-config.js
    module.exports = {
    plugins: [
    {
    resolve: `gatsby-transformer-remark`,
    options: {
    plugins: [
    + `remark-default-class-name`
    ],
    },
    },

    1.找到markdown节点

    该插件将被赋予 markdownAST对象,它允许您查找和修改节点。

    我会用 unist-util-select以帮助找到正确的节点。它带有 gatsby-transformer-remark ,但如果由于某些原因它不起作用,只需重新安装它。

    从这里开始,找到节点很简单:

    const { selectAll } = require('unist-util-select');

    module.exports = ({ markdownAST }) => {
    // `heading` is equivalent to `h1...h6` in markdown.
    // specify [depth] allow us to target the right heading tag.
    const h1Nodes = selectAll('heading[depth=1]', markdownAST);

    console.log(h1Nodes)
    // this yields
    // [{ type: "heading", children: [{ type: "text", value: "..." }] }, ...]
    }

    2.在其data.hProperties中添加className

    我们可以直接修改节点。

      const h1Nodes = selectAll('heading[depth=1]', markdownAST);

    - console.log(h1Nodes)
    // node doesn't always have data
    + if (!node.data) node.data = {};
    + node.data.hProperties = {
    + className: 'foo'
    + }

    就是这样,全部 h1应该有一个 foo现在上课。

    这对我来说是一个特别有趣的问题,因为我正在了解 Unist及其生态系统,为 remark 提供动力;所以谢谢你。

    我做了一个 simple plugin that's a bit more generic here ,请随意尝试并让我知道是否有问题。

    关于gatsby - 配置 gatsby-transformer-remark 添加默认类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479917/

    24 4 0
    文章推荐: reactjs - 未捕获的类型错误 : Cannot assign to read only property '' of object '#'