MDX

使用 MDX 创建页面。

配置参数

extensions string[]

List of extensions this plugin applies to

Default:
[ ".mdx" ]
recmaPlugins object

List of recma plugins to use

remarkPlugins object

List of remark plugins to use

Default:
[remarkGfm]
rehypeOptions object

Options to pass to rehype

rehypePlugins object

List of rehype plugins to use

useDefaultPlugins boolean

Set false to remove the default plugins

Default:
true
components record

Components to add/override

includes string

Custom includes path

Default:
site.options.includes

描述

MDX 是一种结合了 Markdown 和 JSX 的格式,因此你可以编写常规的 Markdown 内容并导入 JSX 组件。这个插件通过创建扩展名为 .mdx 的文件,为 Lume 添加了创建 MDX 页面的支持。

安装

MDX 插件依赖于 JSX 插件才能工作。请将它与 jsxjsx_preact 插件一起使用,具体取决于你想使用 React 还是 Preact。

这是一个 Preact 的示例:

import lume from "lume/mod.ts";
import jsx from "lume/plugins/jsx_preact.ts";
import mdx from "lume/plugins/mdx.ts";

const site = lume();

site.use(jsx());
site.use(mdx(/* Options (选项) */));

export default site;

默认情况下,Deno 使用 React 渲染 JSX。 如果你想使用 jsx_preact 插件,请将以下内容添加到你的 deno.json 文件中:

"compilerOptions": {
  "jsx": "react-jsx",
  "jsxImportSource": "npm:preact"
}

插件

MDX 在底层使用了 Remark 和 Rehype,因此你可以添加额外的插件。 默认情况下,它使用 GitHub-flavored markdown,但是你可以使用 remarkPluginsrecmaPluginsrehypePlugins 选项来添加更多插件:

import lume from "lume/mod.ts";
import mdx from "lume/plugins/mdx.ts";
import jsx from "lume/plugins/jsx.ts";
import a11yEmoji from 'npm:@fec/remark-a11y-emoji';
import rehypeRemoveComments from 'npm:rehype-remove-comments@5';

const site = lume();

site.use(jsx());
site.use(mdx({
  remarkPlugins: [allyEmoji],
  rehypePlugins: [rehypeRemoveComments]
}));

export default site;

组件

在 MDX 中,你可以使用来自全局变量 comp 的 Lume 组件,或者像在 JavaScript 中一样导入其他组件 (使用 import ... from ...):

---
title: Hello world
description: This is a description
---

import Image from "./_includes/Image.tsx";

<comp.Header title={title} description={description}/>

这是一个 markdown 文件,标题是 **{ title }**。

<Image alt="foo" />

MDX 被设计为与 JSX 组件一起工作。 如果你使用的组件返回的是 HTML 代码字符串 (例如 nunjucks 组件),它将被转义。 为了避免这种情况,你必须使用 dangerouslySetInnerHTML 属性。

例如,假设你有一个 nunjucks 组件来渲染标题:

<!-- comp.title -->
<h1>{{ text }}</h1>

在 mdx 文件中使用它的方法是:

<div dangerouslySetInnerHTML={
  { __html: comp.title({ text: "Hello world" }) }
} />

覆盖组件

你可以使用 components 选项来覆盖或添加额外的组件。 例如,要将所有 h1 转换为 h2

import lume from "lume/mod.ts";
import mdx from "lume/plugins/mdx.ts";
import jsx from "lume/plugins/jsx.ts";

const site = lume();

site.use(jsx());
site.use(mdx({
  components: {
    h1: "h2",
  },
}));

export default site;