常见使用

创建Remark插件

setContent

import { visit } from "unist-util-visit";
 
export function setContent() {
  return function (tree, file) {
    let content = "";
 
    visit(tree, "paragraph", (node) => {
      node.children.forEach((child) => {
        content += child.value;
      });
    });
 
    file.data.astro.frontmatter.strippedContent = content;
  };
}

转换wiki语法![[]]

import { unified } from "unified";
import { remark } from "remark";
import remarkParse from "remark-parse";
import remarkHtml from "remark-html";
import { visit } from "unist-util-visit";
import { toMarkdown } from "mdast-util-to-markdown";
import { gfmFootnoteToMarkdown } from "mdast-util-gfm-footnote";
import { gfmStrikethroughToMarkdown } from "mdast-util-gfm-strikethrough";
import remarkFrontmatter from "remark-frontmatter";
import remarkGfm from "remark-gfm";
 
const EMBED_LINK_REGEX = /!\[\[([\S]+)\]\]/g;
 
export function remarkObsidianImage(options = { aFolder: "attachments" }) {
  return function (tree, file) {
    visit(tree, "paragraph", (node, index, parent) => {
      const markdown = toMarkdown(node, {
        extensions: [gfmFootnoteToMarkdown(), gfmStrikethroughToMarkdown],
      });
      const paragraph = String(
        unified().use(remarkParse).use(remarkHtml).processSync(markdown)
      );
 
      if (paragraph.match(EMBED_LINK_REGEX)) {
        const [, fileName] = EMBED_LINK_REGEX.exec(paragraph);
 
        const content = `![](${options.aFolder}/${fileName})`;
 
        console.log("content", content);
 
        const embedTree = remark()
          .use(remarkFrontmatter)
          .use(remarkGfm)
          .parse(content);
 
        parent.children.splice(index, 1, embedTree);
 
        return node;
      }
    });
  };
}

astro.config.ts 中使用。

import { remarkObsidianImage } from "./src/utils/remark-obsidian-image";
 
export default defineConfig({
  markdown: {
    remarkPlugins: [[remarkObsidianImage, { aFolder: "attachments" }]],
  },
});

修改Markdown

一级标题转换为二级标题。

# Hi, Saturn!
## Hi, Saturn!
/**
 * @import {Root} from 'mdast'
 */
 
import remarkParse from 'remark-parse'
import remarkStringify from 'remark-stringify'
import {unified} from 'unified'
import {visit} from 'unist-util-visit'
 
const file = await unified()
  .use(remarkParse)
  .use(myRemarkPluginToIncreaseHeadings)
  .use(remarkStringify)
  .process('# Hi, Saturn!')
 
console.log(String(file)) // => '## Hi, Saturn!'
 
function myRemarkPluginToIncreaseHeadings() {
  /**
   * @param {Root} tree
   */
  return function (tree) {
    visit(tree, function (node) {
      if (node.type === 'heading') {
        node.depth++
      }
    })
  }
}

常用插件

扩展阅读