Skip to navigation

入门

¥Getting started

本文介绍如何将 MDX 集成到你的项目中。它展示了如何将 MDX 与你选择的打包器和 JSX 运行时结合使用。 要了解 MDX 格式的工作原理,我们建议你从 § 什么是 MDX 开始。当你完成设置并准备好使用 MDX 时,请参阅 § 使用 MDX

¥This article explains how to integrate MDX into your project. It shows how to use MDX with your bundler and JSX runtime of choice. To understand how the MDX format works, we recommend that you start with § What is MDX. See § Using MDX when you’re all set up and ready to use MDX.

内容

¥Contents

先决条件

¥Prerequisites

MDX 依赖于 JSX,因此你的项目也需要支持 JSX。任何 JSX 运行时(React、Preact、Vue 等)都可以。请注意,我们确实为你将 JSX 编译为 JavaScript,因此你无需进行设置。

¥MDX relies on JSX, so it’s required that your project supports JSX as well. Any JSX runtime (React, Preact, Vue, etc.) will do. Note that we do compile JSX to JavaScript for you so you don’t have to set that up.

所有 @mdx-js/* 包都是用现代 JavaScript 编写的。需要 Node.js 版本 16.0 或更高版本才能使用它们。我们的包也是 仅限 ESM,所以它们必须是 import,而不是 required。

¥All @mdx-js/* packages are written in modern JavaScript. A Node.js version of 16.0 or later is needed to use them. Our packages are also ESM only, so they have to be imported instead of required.

注意:使用 Rust 而不是 Node.js?尝试 mdxjs-rs

¥Note: Using Rust instead of Node.js? Try mdxjs-rs!

快速开始

¥Quick start

打包器

¥Bundler

MDX 是一种编译为 JavaScript 的语言。(我们还将常规 Markdown 编译为 JavaScript。)最简单的入门方法是使用打包器的集成(如果你有的话):

¥MDX is a language that’s compiled to JavaScript. (We also compile regular markdown to JavaScript.) The easiest way to get started is to use an integration for your bundler if you have one:

你还可以在没有打包程序的情况下使用 MDX:

¥You can also use MDX without bundlers:

有关这些工具的更多信息,请参阅其专用部分:¶ Next.js¶ Node.js¶ Rollup¶ Vite¶ esbuild¶ Webpack

¥For more info on these tools, see their dedicated sections: ¶ Next.js, ¶ Node.js, ¶ Rollup, ¶ Vite, ¶ esbuild, and ¶ webpack.

JSX

现在你已经设置了集成或 @mdx-js/mdx 本身,是时候配置 JSX 运行时了。

¥Now you’ve set up an integration or @mdx-js/mdx itself, it’s time to configure your JSX runtime.

通过设置 jsxImportSourceProcessorOptions 支持其他 JSX 运行时。

¥Other JSX runtimes are supported by setting jsxImportSource in ProcessorOptions.

有关这些工具的更多信息,请参阅其专用部分:¶ Emotion¶ Preact¶ React¶ Solid¶ Svelte¶ 主题用户界面¶ Vue

¥For more info on these tools, see their dedicated sections: ¶ Emotion, ¶ Preact, ¶ React, ¶ Solid, ¶ Svelte, ¶ Theme UI, and ¶ Vue.

编辑

¥Editor

你可以通过向编辑器添加对 MDX 的支持来增强使用 MDX 的体验:

¥You can enhance the experience of using MDX by adding support of it to your editor:

为我们的 VS Code 扩展提供支持并用于高亮 GitHub 上的代码块的语法高亮保留在 wooorm/markdown-tm-language

¥The syntax highlighting that powers our VS Code extension and that is used to highlight code blocks on GitHub is maintained at wooorm/markdown-tm-language.

类型

¥Types

Expand example of typed imports

First install the package:

Shell
npm install @types/mdx

…TypeScript should automatically pick it up:

example.js
import Post from './post.mdx' // `Post` is now typed.

我们的包上打有 TypeScript。为了使类型起作用,必须键入 JSX 命名空间。这是通过安装和使用框架类型来完成的,例如 @types/react

¥Our packages are typed with TypeScript. For types to work, the JSX namespace must be typed. This is done by installing and using the types of your framework, such as @types/react.

要启用导入的 .mdx.md 等类型,请安装并使用 @types/mdx。该包还导出几个有用的类型,例如代表 components 属性的 MDXComponents。你可以像这样导入它们:

¥To enable types for imported .mdx, .md, etc., install and use @types/mdx. This package also exports several useful types, such as MDXComponents which represents the components prop. You can import them like so:

example.ts
import type {MDXComponents} from 'mdx/types.js'

安全

¥Security

MDX 是一种编程语言。如果你信任你的作者,那很好。如果不这样做,那就不安全。

¥MDX is a programming language. If you trust your authors, that’s fine. If you don’t, it’s unsafe.

不要让互联网上的随机人员编写 MDX。如果你这样做,你可能想考虑将 <iframe>sandbox 一起使用,但安全性很难,而且这似乎并不是 100%。对于 Node.js,vm2 听起来很有趣。但是你可能还应该使用 Docker 或类似工具对整个操作系统进行沙箱处理,执行限速,并确保在花费太长时间时可以终止进程。

¥Do not let random people from the internet write MDX. If you do, you might want to look into using <iframe>s with sandbox, but security is hard, and that doesn’t seem to be 100%. For Node.js, vm2 sounds interesting. But you should probably also sandbox the whole OS using Docker or similar, perform rate limiting, and make sure processes can be killed when taking too long.

集成

¥Integrations

打包者

¥Bundlers

esbuild
Expand example
example.js
import mdx from '@mdx-js/esbuild'
import esbuild from 'esbuild'

await esbuild.build({
  entryPoints: ['index.mdx'],
  format: 'esm',
  outfile: 'output.js',
  plugins: [mdx({/* jsxImportSource: …, otherOptions… */})]
})

我们支持 esbuild。安装并配置 esbuild 插件 @mdx-js/esbuild配置你的 JSX 运行时 取决于你使用哪一种(React、Preact、Vue 等)。

¥We support esbuild. Install and configure the esbuild plugin @mdx-js/esbuild. Configure your JSX runtime depending on which one (React, Preact, Vue, etc.) you use.

要使用比用户支持的更现代的 JavaScript 功能,配置 esbuild 的 target.

¥To use more modern JavaScript features than what your users support, configure esbuild’s target.

Rollup
Expand example
rollup.config.js
import mdx from '@mdx-js/rollup'
import {babel} from '@rollup/plugin-babel'

/** @type {import('rollup').RollupOptions} */
const config = {
  // …
  plugins: [
    // …
    mdx({/* jsxImportSource: …, otherOptions… */})
    // Babel is optional:
    babel({
      // Also run on what used to be `.mdx` (but is now JS):
      extensions: ['.js', '.jsx', '.cjs', '.mjs', '.md', '.mdx'],
      // Other options…
    })
  ]
}

export default config

我们支持 Rollup。安装并配置 Rollup 插件 @mdx-js/rollup配置你的 JSX 运行时 取决于你使用哪一种(React、Preact、Vue 等)。

¥We support Rollup. Install and configure the Rollup plugin @mdx-js/rollup. Configure your JSX runtime depending on which one (React, Preact, Vue, etc.) you use.

要使用比用户支持的更现代的 JavaScript 功能,安装并配置 @rollup/plugin-babel.

¥To use more modern JavaScript features than what your users support, install and configure @rollup/plugin-babel.

如果你通过它使用 Rollup,另请参阅 ¶ Vite 以获取更多信息。

¥See also ¶ Vite, if you use Rollup through it, for more info.

Webpack
Expand example
webpack.config.js
/** @type {import('webpack').Configuration} */
const webpackConfig = {
  module: {
    // …
    rules: [
      // …
      {
        test: /\.mdx?$/,
        use: [
          // Babel is optional:
          {loader: 'babel-loader', options: {}},
          {
            loader: '@mdx-js/loader',
            /** @type {import('@mdx-js/loader').Options} */
            options: {/* jsxImportSource: …, otherOptions… */}
          }
        ]
      }
    ]
  }
}

export default webpackConfig

我们支持 webpack。安装并配置 webpack 加载器 @mdx-js/loader配置你的 JSX 运行时 取决于你使用哪一种(React、Preact、Vue 等)。

¥We support webpack. Install and configure the webpack loader @mdx-js/loader. Configure your JSX runtime depending on which one (React, Preact, Vue, etc.) you use.

要使用比用户支持的更现代的 JavaScript 功能,安装并配置 babel-loader.

¥To use more modern JavaScript features than what your users support, install and configure babel-loader.

如果你通过它使用 webpack,另请参阅 ¶ Next.js 以获取更多信息。

¥See also ¶ Next.js, if you use webpack through it, for more info.

构建系统

¥Build systems

Vite
Expand example
vite.config.js
import mdx from '@mdx-js/rollup'
import {defineConfig} from 'vite'

const viteConfig = defineConfig({
  plugins: [
    mdx(/* jsxImportSource: …, otherOptions… */)
  ]
})

export default viteConfig

我们支持 Vite。安装并配置 Rollup 插件 @mdx-js/rollup配置你的 JSX 运行时 取决于你使用哪一种(React、Preact、Vue 等)。

¥We support Vite. Install and configure the Rollup plugin @mdx-js/rollup. Configure your JSX runtime depending on which one (React, Preact, Vue, etc.) you use.

要使用比用户支持的更现代的 JavaScript 功能,配置 Vite 的 build.target.

¥To use more modern JavaScript features than what your users support, configure Vite’s build.target.

注意:如果还使用 vitejs/vite-plugin-react,则必须强制 @mdx-js/rollup 在其之前的 pre 阶段运行:

¥Note: If you also use vitejs/vite-plugin-react, you must force @mdx-js/rollup to run in the pre phase before it:

vite.config.js
// …
const viteConfig = defineConfig({
  plugins: [
    {enforce: 'pre', ...mdx(/* jsxImportSource: …, otherOptions… */)},
    react()
  ]
})
// …

另请参阅 Vite 中使用的 ¶ Rollup,如果你使用它,请参阅 ¶ Vue 以获取更多信息。

¥See also ¶ Rollup which is used in Vite and see ¶ Vue if you’re using that, for more info.

编译器

¥Compilers

Babel
Expand plugin and sample use

This plugin:

plugin.js
import path from 'node:path'
import parser from '@babel/parser'
import {compileSync} from '@mdx-js/mdx'
import estreeToBabel from 'estree-to-babel'

export function babelPluginSyntaxMdx() {
  // Tell Babel to use a different parser.
  return {parserOverride: babelParserWithMdx}
}

// A Babel parser that parses MDX files with `@mdx-js/mdx` and passes any
// other things through to the normal Babel parser.
function babelParserWithMdx(value, options) {
  if (options.sourceFileName && /\.mdx?$/.test(options.sourceFileName)) {
    // Babel does not support async parsers, unfortunately.
    return compileSync(
      {value, path: options.sourceFileName},
      // Tell `@mdx-js/mdx` to return a Babel tree instead of serialized JS.
      {recmaPlugins: [recmaBabel], /* jsxImportSource: …, otherOptions… */}
    ).result
  }

  return parser.parse(value, options)
}

// A “recma” plugin is a unified plugin that runs on the estree (used by
// `@mdx-js/mdx` and much of the JS ecosystem but not Babel).
// This plugin defines `'estree-to-babel'` as the compiler,
// which means that the resulting Babel tree is given back by `compileSync`.
function recmaBabel() {
  this.compiler = estreeToBabel
}

…can be used like so with the Babel API:

example.js
import babel from '@babel/core'
import {babelPluginSyntaxMdx} from './plugin.js'

// Note that a filename must be set for our plugin to know it’s MDX instead of JS.
await babel.transformAsync(file, {filename: 'example.mdx', plugins: [babelPluginSyntaxMdx]})

你可能应该直接使用 Rollup 或 webpack 而不是 Babel,因为这样可以提供最好的界面。可以在 Babel 中使用 @mdx-js/mdx,而且速度更快一些,因为如果无论如何使用 Babel,它会跳过 @mdx-js/mdx 序列化和 Babel 解析。

¥You should probably use Rollup or webpack instead of Babel directly as that gives the best interface. It is possible to use @mdx-js/mdx in Babel and it’s a bit faster, as it skips @mdx-js/mdx serialization and Babel parsing, if Babel is used anyway.

Babel 不支持其解析器的语法扩展(它有“语法”插件,但这些插件只能打开或关闭内部标志)。它确实支持设置不同的解析器。这又让我们选择是使用 @mdx-js/mdx 还是 @babel/parser

¥Babel does not support syntax extensions to its parser (it has “syntax” plugins but those only turn internal flags on or off). It does support setting a different parser. Which in turn lets us choose whether to use the @mdx-js/mdx or @babel/parser.

站点生成器

¥Site generators

Astro

Astro 有自己的 MDX 集成。你可以添加与 Astro CLI 的集成:npx astro add mdx

¥Astro has its own MDX integration. You can add the integration with the Astro CLI: npx astro add mdx.

此基本设置允许你导入 Markdown、Astro 组件和 MDX 文件作为组件。有关如何在 MDX 文件中使用框架中的组件的信息,请参阅 Astro 的 框架组件指南

¥This base setup lets you import markdown, Astro components, and MDX files as components. See Astro’s Framework components guide for info on how to use components from frameworks in your MDX files.

有关如何结合 Astro 和 MDX 的更多信息,请参阅 Astro 的 MDX 集成文档

¥For more on how to combine Astro and MDX, see Astro’s MDX integration docs.

Docusaurus

Docusaurus 默认支持 MDX。有关如何将 MDX 与 Docusaurus 结合使用的信息,请参阅 Docusaurus 的 MDX 和 React 指南

¥Docusaurus supports MDX by default. See Docusaurus’ MDX and React guide for info on how to use MDX with Docusaurus.

Gatsby

Gatsby 有自己的插件来支持 MDX。请参阅 gatsby-plugin-mdx 了解如何将 MDX 与 Gatsby 结合使用。

¥Gatsby has its own plugin to support MDX. See gatsby-plugin-mdx on how to use MDX with Gatsby.

Next.js
Expand example
next.config.js
import nextMdx from '@next/mdx'

const withMdx = nextMdx({
  // By default only the `.mdx` extension is supported.
  extension: /\.mdx?$/,
  options: {/* otherOptions… */}
})

const nextConfig = withMdx({
  // Support MDX files as pages:
  pageExtensions: ['md', 'mdx', 'tsx', 'ts', 'jsx', 'js'],
})

export default nextConfig

Next.js 有自己的 MDX 集成。安装并配置 @next/mdx

¥Next.js has its own MDX integration. Install and configure @next/mdx.

不要将 providerImportSource@mdx-js/react 与 Next 一起使用来注入组件。请改为添加 mdx-components.tsx(在 src// 中)文件。请参阅 nextjs.org 上配置 MDX 了解更多信息。

¥Do not use providerImportSource and @mdx-js/react with Next to inject components. Add an mdx-components.tsx (in src/ or /) file instead. See Configuring MDX on nextjs.org for more info.

Parcel

Parcel 有自己的插件来支持 MDX。请参阅 @parcel/transformer-mdx 了解如何将 MDX 与 Parcel 结合使用。

¥Parcel has its own plugin to support MDX. See @parcel/transformer-mdx on how to use MDX with Parcel.

JSX 运行时

¥JSX runtimes

Emotion
Expand example
example.js
import {compile} from '@mdx-js/mdx'

const js = String(await compile('# hi', {jsxImportSource: '@emotion/react', /* otherOptions… */}))

jsxImportSourceProcessorOptions 设置为 '@emotion/react' 时,支持 Emotion。你可以选择安装和配置 @mdx-js/react 以支持基于上下文的组件传递。

¥Emotion is supported when jsxImportSource in ProcessorOptions is set to '@emotion/react'. You can optionally install and configure @mdx-js/react to support context based component passing.

另请参阅 ¶ React(用于 Emotion),并参阅 ¶ Rollup¶ Webpack(你可能正在使用)以获取更多信息。

¥See also ¶ React, which is used in Emotion, and see ¶ Rollup and ¶ webpack, which you might be using, for more info.

Ink
Expand example
example.mdx
# Hi!
example.js
import React from 'react'
import {Text, render} from 'ink'
import Content from './example.mdx' // Assumes an integration is used to compile MDX -> JS.

const components = {
  h1(properties) {
    return React.createElement(Text, {bold: true, ...properties})
  },
  p: Text
}

render(React.createElement(Content, {components}))

Can be used with:

Shell
node --loader=@mdx-js/node-loader example.js

Ink 使用 React JSX 运行时,因此进行设置。你需要将 HTML 元素替换为 Ink 的组件。请参阅 § 组件表 了解它们是什么,以及 Ink 的文档了解它们可以用什么替换。

¥Ink uses the React JSX runtime, so set that up. You will need to swap HTML elements out for Ink’s components. See § Table of components for what those are and Ink’s docs on what they can be replaced with.

另请参阅 ¶ Node.js¶ React 了解更多信息。

¥See also ¶ Node.js and ¶ React for more info.

Preact
Expand example
example.js
import {compile} from '@mdx-js/mdx'

const js = String(await compile('# hi', {jsxImportSource: 'preact', /* otherOptions… */}))

jsxImportSourceProcessorOptions 设置为 'preact' 时支持 Preact。你可以选择安装和配置 @mdx-js/preact 以支持基于上下文的组件传递。

¥Preact is supported when jsxImportSource in ProcessorOptions is set to 'preact'. You can optionally install and configure @mdx-js/preact to support context based component passing.

另请参阅你可能正在使用的 ¶ Rollup¶ esbuild¶ Webpack,了解更多信息。

¥See also ¶ Rollup, ¶ esbuild, and ¶ webpack, which you might be using, for more info.

React

默认支持 React。你可以选择安装和配置 @mdx-js/react 以支持基于上下文的组件传递。

¥React is supported by default. You can optionally install and configure @mdx-js/react to support context based component passing.

另请参阅你可能正在使用的 ¶ Rollup¶ esbuild¶ Webpack,了解更多信息。

¥See also ¶ Rollup, ¶ esbuild, and ¶ webpack, which you might be using, for more info.

主题界面

¥Theme UI

Expand example

Example w/o @mdx-js/react

example.js
import {base} from '@theme-ui/preset-base'
import {ThemeProvider, components} from 'theme-ui'
import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS.

<ThemeProvider theme={base}>
  <Post components={components} />
</ThemeProvider>

Example w/ @mdx-js/react

example.js
import {base} from '@theme-ui/preset-base'
import {ThemeProvider} from 'theme-ui'
import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS.

<ThemeProvider theme={base}>
  <Post />
</ThemeProvider>

主题界面 是一个特定于 React 的库,它依赖于上下文来访问其有效组件。你可以安装和配置 @mdx-js/react 以支持基于上下文的组件传递。

¥Theme UI is a React-specific library that depends on context to access its effective components. You can install and configure @mdx-js/react to support context based component passing.

另请参阅你可能正在使用的 ¶ Emotion¶ React¶ Rollup¶ esbuild¶ Webpack,了解更多信息。

¥See also ¶ Emotion, ¶ React, ¶ Rollup, and ¶ esbuild, ¶ webpack, which you might be using, for more info.

Svelte
Expand example
example.js
import {compile} from '@mdx-js/mdx'

const js = String(await compile('# hi', {jsxImportSource: 'svelte-jsx', /* otherOptions… */}))

jsxImportSourceProcessorOptions 设置为 'svelte-jsx' 时,支持 Svelte。

¥Svelte is supported when jsxImportSource in ProcessorOptions is set to 'svelte-jsx'.

另请参阅你可能正在使用的 ¶ Rollup¶ esbuild¶ Webpack,了解更多信息。

¥See also ¶ Rollup, ¶ esbuild, and ¶ webpack, which you might be using, for more info.

Vue
Expand example
example.js
import {compile} from '@mdx-js/mdx'

const js = String(await compile('# hi', {jsxImportSource: 'vue', /* otherOptions… */}))

jsxImportSourceProcessorOptions 设置为 'vue' 时,支持 Vue。你可以选择安装和配置 @mdx-js/vue 以支持基于上下文的组件传递。

¥Vue is supported when jsxImportSource in ProcessorOptions is set to 'vue'. You can optionally install and configure @mdx-js/vue to support context based component passing.

另请参阅你可能正在使用的 ¶ Vite 以获取更多信息。

¥See also ¶ Vite, which you might be using, for more info.

Solid
Expand example
example.js
import {compile} from '@mdx-js/mdx'

const js = String(await compile('# hi', {jsxImportSource: 'solid-js/h', /* otherOptions… */}))

jsxImportSourceProcessorOptions 设置为 'solid-js/h' 时支持实心。

¥Solid is supported when jsxImportSource in ProcessorOptions is set to 'solid-js/h'.

另请参阅你可能正在使用的 ¶ Rollup¶ Vite 以获取更多信息。

¥See also ¶ Rollup and ¶ Vite, which you might be using, for more info.

JavaScript 引擎

¥JavaScript engines

Node.js

可以使用 @mdx-js/node-loader.MDX 文件导入 Node 中。有关如何配置它的信息,请参阅其自述文件。

¥MDX files can be imported in Node by using @mdx-js/node-loader. See its readme on how to configure it.

进一步阅读

¥Further reading

MDX 中文网 - 粤ICP备13048890号