簡體   English   中英

如何在評論插件中過濾 frontmatter?

[英]How can I filter frontmatter in a remark plugin?

在 AstroJS 站點中,我設置了一個備注插件,如果未明確設置,則將默認布局應用於.md(x)文檔。 該代碼來自問題 #397中的 RFC,並且運行良好。 我現在想使用<Content/>組件將大型文檔分解成片段。

我可以讓內容組件工作,但是每個片段都應用了默認布局,所以我在整頁中嵌套了整頁! 一種解決方案是將layout: ""應用於我的片段,但我也在構建一個站點搜索索引,這些索引需要從中排除(因為結果將返回整頁)。 這意味着像fragment: true這樣的自定義 frontmatter 更可取,因為它的定義更明確。

這是我目前設置的代碼:

export default function defaultLayoutPlugin() {
  return function (tree, file) {
      console.log(file?.data?.astro?.frontmatter);
      const hasLayout = file?.data?.astro?.frontmatter?.layout;
      const isFragment = file?.data?.astro?.frontmatter?.fragment ? true : false;
      if (hasLayout) {
        return;
      }
      if (isFragment) {
        return;
      }
      // do default layout stuff
   }
}

console.log行只是為每個頁面返回undefined ,盡管它們都至少具有titledescription屬性,如果不是也有layout 話雖如此,具有顯式布局的頁面並未應用默認布局,因此在某處拾取了 frontmatter,但我無法記錄它。 出於未知原因, isFragment始終為 false,即使它明確設置為true也是如此。

  • 什么可能導致 frontmatter 不被記錄?
  • 我怎樣才能正確調試(自定義)注釋插件中的 frontmatter,然后對這些值做些什么?

謝謝

  • 從 Astro 版本2.0.0-beta.1 ,您使用 frontmatter 的方式是正確的我用於測試示例並且我得到了這個工作。 唯一的細微差別是命名導出和未提供的配置文件。

  • 如果您使用另一個插件注入了 frontmatter,那么請查看自 Astro 發布2.0.0-beta.0以來的重大更改,其中指出 injectedFrontmatter the injectedFrontmatter property has been renamed to remarkPluginFrontmatter

參考https://github.com/withastro/astro/releases/tag/astro%402.0.0-beta.0

  • 通常,您可以通過放置虛擬插件來調試評論,以便在被測插件前后進行檢查

測試

我用文件測試了你的代碼如何有和沒有這個插件的布局,類似於你剛剛調整以記錄你的 boolean 變量並找到我命名的導出導入。

function remarkLayoutCheck() {
  return function transformer(syntaxTree,file) {
    console.log("   ---   remark Layout Check   ---")
    console.log(file?.data?.astro?.frontmatter);
    const hasLayout = file?.data?.astro?.frontmatter?.layout;
    const isFragment = file?.data?.astro?.frontmatter?.fragment ? true : false;
    console.log(`hasLayout = ${hasLayout}`)
    console.log(`isFragment = ${isFragment}`)

    return syntaxTree;
  };
}

export{
  remarkLayoutCheck
}

這是 output

   ---   remark Layout Check   ---
{ title: 'Testing Layout', layout: '../src/layouts/Layout.astro' }
hasLayout = ../src/layouts/Layout.astro
isFragment = false
   ---   remark Layout Check   ---
{ title: 'Testing No Layout' }
hasLayout = undefined
isFragment = false

例子

https://github.com/MicroWebStacks/astro-examples/blob/2bc0c72c99419d5af85feaa142ea5f23e5249525/22_mdx-svg/remark/remark-layout-check.js#L8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM