bitpie钱包app下载中文版|mdx
让 Markdown 步入 组件时代 | MDX中文文档 | MDX中文网
rkdown 步入 组件时代 | MDX中文文档 | MDX中文网Skip to navigation让 Markdown 步入组件时代MDX 是一种书写格式,允许你在 Markdown 文档中无缝地插入 JSX 代码。 你还可以导入(import)组件,例如交互式图表或弹框,并将它们嵌入到 你所书写的内容当中。 这让利用组件来编写较长的内容成为了一场革命。 继续阅读 »New: MDX 2!经过数年的努力开发,MDX 2 版本正式发布了,新版本带来了很多 改进。 下面划重点: 改进语法 让 JSX 中插入 markdown 更容易 JavaScript 表达式 将 {2 * Math.PI} 转换为 6.283185307179586 新集成了 esbuild、Rollup 和 Node.js⚛️ 支持所有 JSX 运行时: React、Preact、Vue、Emotion,以及你能叫上来名字的,都被支持 改进的 AST 暴露了更多详细信息♀️ 编译速度至少提升 25% 生成的代码运行速度是原来的两倍 (提速 100%) @mdx-js/mdx 打包后的体积比原来的三分之一还少 (减少了 250%) 还有很多,很多……继续阅读 »MDX 有什么用?你可以通过 JSX 在 markdown 中嵌入组件:example.mdximport {Chart} from './snowfall.js'export const year = 2018
# Last year’s snowfall
In {year}, the snowfall was above average.
It was followed by a warm spring which caused
flood conditions in many of the nearby rivers.
上述代码被编译成 JavaScript,你就可以在任何支持 JSX 的框架中 使用了:Last year’s snowfallIn 2018, the snowfall was above average. It was followed by a warm spring which caused flood conditions in many of the nearby rivers.我们制作了一个交互式的练习工具,你可以利用这个工具尝试 MDX 并看到 转换后的结果。 在线工具 »入门MDX 支持大部分的打包工具(bundlers)、框架和编辑器。 无论是 Next.js、Docusaurus 或 Gatsby。 无论是 esbuild、Rollup 或 webpack。 无论是 React、Preact 或 Vue。 继续阅读 »MDX 优点汇总❤️ 强大: MDX 将 markdown 和 JSX 语法完美地融合在一起,完美地适配 基于 JSX 的项目 一切皆组件: 可以将现有的组件使用到 MDX 中,并且可以将其它 MDX 文件作为组件导入(import) 可自定义: 可以为每个 markdown 语法指定一个用于渲染的组件(例如 {h1: MyHeading}) 基于 Markdown: 保留了 markdown 的简洁和优雅, 你只需在需要时使用 JSX 非常非常快: MDX 没有运行时的开销,所有编译都发生在构建阶段 在构建阶段It’s extremely useful for using design system components to render markdown and weaving interactive components in with existing markdown.— @chrisbiscardiMDX is made with ❤️ in Boise, Amsterdam, and around the This site does not track you.MIT © 2017-2024冀ICP备14002930号-9Project on GitHubSite on GitHubUpdates on TwitterUpdates as RSS feedSponsor on OpenCollective友链BootstrapTailwind CSSReactStyleXNext.jsDocusaurusnpmYarnpnpmBabelWebpackRollupParcelesbuildSvelteAlpine.jsMarkdownSassWebAssemblyPrettierDenoKoaLodashStrapiAxiosNunjucksPugMobXReduxJSDocSkip to content中文文档MDX 是什么?入门Using MDXExtending MDXTroubleshooting MDX使用指南GitHub flavored markdown (GFM)FrontmatterMathSyntax highlightingEmbedMDX on demand核心软件包@mdx-js/esbuild@mdx-js/loader@mdx-js/mdx@mdx-js/node-loader@mdx-js/preact@mdx-js/react@mdx-js/registerremark-mdx@mdx-js/rollup@mdx-js/vue组件在线练习场社区SupportContributeSponsorAboutProjects博客英文官网GitHubTwitterOpenCollect
什么是 MDX? | MDX ä¸æ–‡ç½‘
¹ˆæ˜¯ MDX? | MDX ä¸æ–‡ç½‘Skip to navigation什么是 MDX?英:What is MDX?本文介ç»�什么是 MDX æ ¼å¼�。它展示了如何在 MDX ä¸ä½¿ç”¨ ESM ä¸çš„ markdownã€�JSXã€�JavaScript 表达å¼�以å�Š import å’Œ export è¯å�¥ã€‚ 有关如何将 MDX 集æˆ�到项目ä¸çš„详细信æ�¯ï¼Œè¯·å�‚阅 § 入门。英:This article explains what the MDX format is. It shows how markdown, JSX, JavaScript expressions, and import and export statements in ESM can be used inside MDX. See § Getting started for details on how to integrate MDX into your project.内容英:Contents先决æ�¡ä»¶è‹±ï¼šPrerequisites组件时代的 Markdown英:Markdown for the component eraMDX è¯æ³•è‹±ï¼šMDX syntaxMarkdownJSX表达å¼�英:ExpressionsESM交织英:Interleaving进一æ¥é˜…读英:Further reading先决æ�¡ä»¶è‹±ï¼šPrerequisitesè¦�编写和使用 MDXï¼Œä½ åº”è¯¥ç†Ÿæ‚‰ Markdown(请å�‚é˜…æ¤ å¤‡å¿˜å�•å’Œæ•™ç¨‹ è�·å�–帮助)和 JavaScript(特别是 JSX)。英:To write and enjoy MDX, you should be familiar with both markdown (see this cheat sheet and tutorial for help) and JavaScript (specifically JSX).组件时代的 Markdown英:Markdown for the component eraMDX å…�è®¸ä½ åœ¨ Markdown 内容ä¸ä½¿ç”¨ JSXã€‚ä½ å�¯ä»¥å¯¼å…¥äº¤äº’å¼�图表或è¦æŠ¥ç‰ç»„ä»¶ï¼Œå¹¶å°†å®ƒä»¬åµŒå…¥åˆ°ä½ çš„å†…å®¹ä¸ã€‚这使得使用组件编写长篇内容å�˜å¾—é��常有趣。🚀英:MDX allows you to use JSX in your markdown content. You can import components, such as interactive charts or alerts, and embed them within your content. This makes writing long-form content with components a blast. 🚀更å®�际的是,MDX å�¯ä»¥è§£é‡Šä¸ºä¸€ç§�å°† markdown ä¸� JSX 结å�ˆåœ¨ä¸€èµ·çš„æ ¼å¼�,如下所示:英:More practically MDX can be explained as a format that combines markdown with JSX and looks as follows:MDX# Hello, world!> Some notable things in a block quote!
æ ‡é¢˜å’Œå�—引用是 markdown,而那些类似 HTML çš„æ ‡ç¾æ˜¯ JSX。对äº�å¼ºè°ƒæˆ–æ ‡é¢˜ç‰å¸¸è§�内容,Markdown 通常感觉比 HTML 或 JSX 更自然。JSX 是 JavaScript 的扩展,看起æ�¥åƒ� HTML,但å�¯ä»¥æ–¹ä¾¿åœ°ä½¿ç”¨ç»„件(å�¯é‡�用的东西)。英:The heading and block quote are markdown, while those HTML-like tags are JSX. Markdown often feels more natural to type than HTML or JSX for common things like emphasis or headings. JSX is an extension to JavaScript that looks like HTML but makes it convenient to use components (reusable things).æ¤ç¤ºä¾‹åœ¨
A blockquote with some emphasis.
ä½ å�¯ä»¥åœ¨ markdown (或 MDX)ä¸ç¼–写ç‰æ•ˆå†…容,如下所示:英:You can write the equivalent in markdown (or MDX) like so:Markdown> A blockquote with *some* emphasis.
MDX 默认支æŒ�æ ‡å‡† Markdown (CommonMark):英:MDX supports standard markdown by default (CommonMark):Markdown# Heading (rank 1)
## Heading 2
### 3
#### 4
##### 5
###### 6
> Block quote
* Unordered
* List
1. Ordered
2. List
A paragraph, introducing a thematic break:
---
```js
some.code()
```
a [link](https://example.com), an
![image](./image.png)
, some *emphasis*,
something **strong**, and finally a little `code()`.
é��æ ‡å‡† Markdown 功能(例如 GFMã€�frontmatterã€�æ•°å¦ã€�è¯æ³•é«˜äº®ï¼‰å�¯ä»¥é€šè¿‡æ�’件å�¯ç”¨ï¼ˆå�‚è§� ¶ 使用æ�’件)。英:Nonstandard markdown features (such as GFM, frontmatter, math, syntax highlighting) can be enabled with plugins (see ¶ Using plugins).一些 Markdown 功能在 MDX ä¸ä¸�起作用:英:Some markdown features don’t work in MDX:缩进代ç �在 MDX ä¸ä¸�起作用:英:Indented code does not work in MDX:MDX console.log(1) // this is a paragraph in MDX!
è¿™æ ·å�šçš„å�Ÿå› æ˜¯è¿™æ ·ä½ å�¯ä»¥å¾ˆå¥½åœ°ç¼©è¿›ä½ 的组件:英:The reason for that is so you can nicely indent your components:MDX
# Hello!
自动链æ�¥åœ¨ MDX ä¸ä¸�起作用。å�Ÿå› 是它们ä¸� JSX æ— æ³•åŒºåˆ†ï¼ˆä¾‹å¦‚ï¼š
Hello, Mars!
...到 JSX(或 MDX),如下所示:英:…to JSX (or MDX) like this:MDX
JSX 适å�ˆç»„件。它使é‡�å¤�的事情å�˜å¾—æ›´åŠ æ¸…æ™°ï¼Œå¹¶å…�许关注点分离。MDX 支æŒ� JSX è¯æ³•ã€‚下é�¢çš„内容看起æ�¥å¾ˆåƒ� HTML:英:JSX is good for components. It makes repeating things more clear and allows for separation of concerns. MDX supports JSX syntax. The following looks a lot like HTML:MDX
Heading!
HTML is a lovely language.
And here is *markdown* in **JSX**!
但æ£å¦‚å‰�é�¢æ��åˆ°çš„ï¼Œä½ ä¹Ÿå�¯ä»¥ä½¿ç”¨ç»„件。请注æ„�ï¼Œå¿…é¡»å®šä¹‰ç»„ä»¶ã€‚ä½ å�¯ä»¥å¯¼å…¥å®ƒä»¬ã€�在本地定义它们或ç¨�å��ä¼ é€’å®ƒä»¬ï¼ˆå�‚è§� § 使用 MDX):英:But as previously mentioned you can use components too. Note that components must be defined. You can import them, define them locally, or pass them in later (see § Using MDX):MDX
You can also use objects with components, such as the `thisOne` component on
the `myComponents` object:
open x={1} label={'this is a string, *not* markdown!'} icon={ /> 有一些边缘情况 MDX ä¸� JSX çš„ä¸�å�Œä¹‹å¤„。英:There are a few edge cases where MDX differs from JSX.表达å¼�英:ExpressionsMDX 还支æŒ�大括å�·å†…çš„ JavaScript 表达å¼�:英:MDX also supports JavaScript expressions inside curly braces:MDXTwo ğŸ�° is: {Math.PI * 2} 表达å¼�å�¯ä»¥åŒ…å�«æ•´ä¸ª JavaScript 程åº�,å�ªè¦�它们(å°�装在)计算结æ�œä¸ºå�¯æ¸²æŸ“内容的表达å¼�ä¸å�³å�¯ã€‚ä½ å�¯ä»¥åƒ�è¿™æ ·ä½¿ç”¨ IIFE:英:Expressions can contain whole JavaScript programs as long as they’re (wrapped in) an expression that evaluates to something that can be rendered. You can use an IIFE like so:MDX {(function () { const guess = Math.random() if (guess > 0.66) { return Look at us. } if (guess > 0.33) { return Who would have guessed?! } return Not me. } )()} 表达å¼�å�¯ä»¥ä¸ºç©ºæˆ–仅包å�«æ³¨é‡Šï¼šè‹±ï¼šExpressions can be empty or contain just a comment:ESMMDX 还支æŒ� JavaScript ä¸çš„ import å’Œ export è¯å�¥ã€‚这些 ESM 功能å�¯ä»¥åœ¨ MDX ä¸ä½¿ç”¨æ�¥å®šä¹‰äº‹ç‰©ï¼šè‹±ï¼šMDX supports import and export statements from JavaScript as well. These ESM features can be used within MDX to define things:MDXimport {External} from './some/place.js' export const Local = properties => An ESM 也å�¯ç”¨äº�é��组件(数æ�®ï¼‰ï¼šè‹±ï¼šESM can also be used for non-components (data):MDXimport {Chart} from './chart.js' import population from './population.js' export const pi = 3.14 交织英:Interleaving如æ�œæ–‡æœ¬å’Œæ ‡ç¾ä½�äº�å�Œä¸€è¡Œï¼Œåˆ™å�¯ä»¥åœ¨ JSX ä¸ä½¿ç”¨ markdown“内è�”â€�,但ä¸�能使用“å�—â€�:英:You can use markdown “inlinesâ€� but not “blocksâ€� inside JSX if the text and tags are on the same line:MDX
ä¸€è¡Œä¸Šçš„æ–‡æœ¬å’Œæ ‡ç¾ä¸�会生æˆ�å�—ï¼Œå› æ¤å®ƒä»¬ä¹Ÿä¸�会生æˆ�
。在ä¸�å�Œçš„çº¿è·¯ä¸Šï¼Œä»–ä»¬è¿™æ ·å�šï¼šè‹±ï¼šText and tags on one line don’t produce blocks so they don’t produce
s either. On separate lines, they do:MDX
This is a `p`.
我们使用这个规则æ�¥åŒºåˆ†ï¼ˆå�Œä¸€æ�¡çº¿æˆ–ä¸�å�Œçº¿ï¼‰ã€‚ä¸�基äº� HTML ä¸å…ƒç´ çš„è¯ä¹‰ã€‚æ‰€ä»¥ä½ å�¯ä»¥æ�„建ä¸�æ£ç¡®çš„ HTMLï¼ˆä½ ä¸�åº”è¯¥è¿™æ ·å�šï¼‰ï¼šè‹±ï¼šWe differentiate using this rule (same line or not). Not based on semantics of elements in HTML. So you can build incorrect HTML (which you shouldn’t):MDX
Don’t do this: it’s a `p` in an `h1`
Do this: an `h1` with `code`
如æ�œæ–‡æœ¬å’Œæ ‡ç¾ä½�äº�å�Œä¸€è¡Œï¼Œä½†ç›¸åº”çš„æ ‡ç¾ä½�äº�ä¸�å�Œè¡Œï¼Œåˆ™æ— 法æ�¢è¡Œâ€œå�—â€�:英:It’s not possible to wrap “blocksâ€� if text and tags are on the same line but the corresponding tags are on different lines:MDXWelcome!
This is home of...
# The Falcons!
è¿™æ˜¯å› ä¸ºè¦�解æ�� markdown,我们首先必须将其分为“å�—â€�。所以在这ç§�情况下有两个段è�½å’Œä¸€ä¸ªæ ‡é¢˜ã€‚在第一段ä¸ç•™ä¸‹ä¸€ä¸ªå¼€å§‹ a æ ‡ç¾ï¼Œå¹¶åœ¨æ ‡é¢˜ä¸ç•™ä¸‹ä¸€ä¸ªæ�‚散的结æ�Ÿ a æ ‡ç¾ã€‚英:That’s because to parse markdown, we first have to divide it into “blocksâ€�. So in this case two paragraphs and a heading. Leaving an opening a tag in the first paragraph and a stray closing a tag in the heading.进一æ¥é˜…读英:Further reading如æ�œä½ 想在项目ä¸ä½¿ç”¨ MDX,请å�‚阅 § 入门英:If you want to use MDX in your project, see § Getting started如æ�œä½ åœ¨ä½¿ç”¨è¯¥æ ¼å¼�æ—¶é�‡åˆ°é”™è¯¯ï¼Œè¯·å�‚阅 § MDX æ•…éšœæ�’除英:If you’re getting errors when working with the format, see § Troubleshooting MDXä¸‹ä¸€ç« ï¼šå…¥é—¨MDX ä¸æ–‡ç½‘ - 粤ICP备13048890å�·Skip to contentMDXå¼€å�‘文档什么是 MDX?入门使用 MDX扩展 MDXMDX æ•…éšœæ�’除å¦ä¹ 指å�—GitHub é£�æ ¼çš„ Markdown (GFM)Frontmatteræ•°å¦è¯æ³•é«˜äº®åµŒå…¥MDX 按需注入组件软件包@mdx-js/esbuild@mdx-js/loader@mdx-js/mdx@mdx-js/node-loader@mdx-js/preact@mdx-js/react@mdx-js/rollup@mdx-js/vueremark-mdx组件列表当å‰�版本 v
浅谈MDX数据库 - 知乎
浅谈MDX数据库 - 知乎切换模式写文章登录/注册浅谈MDX数据库微策略中国已认证账号MDX是”MultiDimensional eXpression”的缩写,这是一种类似于SQL的数据库查询语言。这种查询语言专门用于OLAP (Online analytical processing,在线分析处理)数据,这些数据是存储于OLAP Cube(在线分析处理数据块)中。1. MDX的历史MDX由微软于1997年作为ODBO规范的一部分最先提出。Microsoft Analysis Services(微软分析服务)随后基于这个规范发布了“Microsoft OLAP Services 7.0”。微软又于1999年正式发布了该规范。MDX仅仅只是一个微软的规范,并不是一个开放的标准。但是这个规范正在被越来越多的OLAP服务提供商所采用。这正是MDX生命力顽强的体现。2. MDX数据库MDX标准几乎被所有的大型数据库软件提供商所采用。微软有SSAS(Microsoft SQL Server Analysis Services),甲骨文有Essbase,SAP有SAP BW,IBM有TM1,除此之外还有各种各样的OLAP服务提供商的商用软件支持该标准。详情见表格:3. MDX获取数据MDX规范里定义了两种获取数据的方式:XMLA和OLE DB for OLAP。3.1 XMLAXMLA是“XML for Analysis”的缩写。这是一个企业级标准,用于获取分析系统(例如OLAP)的数据。XMLA支持两种SOAP方法:Execute和Discover。其中:Execute用于执行MDX语句,返回的结果是多维数据的结构和对应的格式化结果Discover用于获取OLAP数据块的结构数据,例如:目录(Catalog),数据块(Cube),维度(Dimension),属性(Properties)等。在XMLA标准中,MDX语句被放在
3.2 OLE DB for OLAPOLE DB for OLAP 是“Object Linking and Embedding Database for Online Analytical Processing abbreviated ODBO”的缩写。这是由微软发布的、用于处理多维数据的企业级标准。其中ODBO是一个在Windows平台用于客户端和OLAP服务器交互的标准API,而且ODBO拓展了OLE DB访问OLAP数据能力。如果用户需要通过OLE DB for OLAP访问支持MDX的数据库,那么MDX的数据库必须提供Windows版本的客户端API库,同时用户必须有一定的编程基础才能正确地拿到数据。4. MDX语句一条基本的MDX语句样例如下:with member [Measures].[DoubleAmount] as '[Measures].[Amount] * 2'
select [Account].[Accounts].Levels(1).AllMembers on columns,
{[Measures].[Amount], [Measures].[DoubleAmount]} on rows
from [Finance]
where ([Date].[Calendar Year].&[2001])“with” 语句部分;样例中的第1行。该语句用于获取数据前的预处理。在预处理的过程中,我们可以定义各种各样的计算,这些计算包括可命名集合和计算成员。在本样例中,我们定义的是计算成员。通过分析这个MDX语句样例,我们可以看出MDX语句有以下几个部分:“select” 语句部分;样例中的第2,3行。该语句用于选择可获取的数据。“from” 语句部分;样例中的第4行。该语句用来定义我们从哪个数据块获取数据。“where” 语句部分;样例中的第5行。该语句用来切割数据块,并合计数据。在这4个部分中,我们都有很大的自由度,可以根据自己的需求写出很复杂的MDX语句以获得相应的数据。5. 可以访问MDX数据的客户端5.1 使用Firefox获取MDX数据对于支持XMLA标准的MDX数据库,我们可以使用Firefox的开发者工具来访问。具体的步骤如下:打开Firefox浏览器打开开发者工具:访问XMLA对应的网址,类似于:http://OLAP-Datasource-Address/OLAP/MSMDPUMP.DLL .在开发者工具中会有一条访问失败的记录:右键点击失败记录,选择“Edit and Resend”按钮:修改“New Request”的方法为“POST”,同时把基于XMLA规范创建的请求放到“Request Body”里面:点击“Send”即可在标准的XMLA规范里,我们需要把用于登录验证的信息放到Request Header里面,而且验证信息需要加密。5.2 使用Excel获取MDX数据另外我们还可以通过Excel来访问大部分的MDX数据库。具体的步骤如下打开新版本的Excel,小编使用的是Excel 2017换到Data那一页,点击“Get Data”下拉框如果是MSAS,就选择”From Database”里面的“From Analysis Services”选项填写对应的登录信息,然后点击下一步选择对应的数据块或者表格,然后点击结束在Excel的右边区域会出现一个可编辑的对话框,我们可以在对话框里进行操作结果会显示在Excel的空白区域Excel相对来说,操作起来比较简单,使用也比较方便;但是Excel在筛选方面限制比较大,不能自由筛选数据。6. 微策略对MDX数据库的支持微策略从03年就开始支持MDX数据库,到MicroStrategy 2019我们已经直接支持了以下MDX数据库:基于这些MDX数据库,微策略提供了灵活的数据探索方式和高度自由化的操作选择。在微策略的产品中,我们只需要简单三步,就能创建出高可读性的报表。创建MDX数据库连接:导入MDX数据块:创建可视化报表:我们一直致力于支持更多的MDX数据库,并提供可靠、快速的服务。更多信息请咨询微策略MDX团队。7. 总结本文章简要讲述了MDX的历史背景、MDX语句的介绍、MDX数据获取方式以及微策略对于MDX数据库支持。微策略对于MDX数据库的支持有悠久的历史,我们相信微策略能够给客户提供关于MDX专业全面的解决方案。参考资料:https://en.wikipedia.org/wiki/MultiDimensional_eXpressionhttps://en.wikipedia.org/wiki/XML_for_Analysishttps://en.wikipedia.org/wiki/OLE_DB_for_OLAPhttps://en.wikipedia.org/wiki/Comparison_of_OLAP_serversKey Concepts in MDX (Analysis Services)我们会每周推送商业智能、数据分析资讯、技术干货和程序员日常生活,欢迎关注我们的知乎公众号“微策略中国”或微信公众号“微策略 商业智能"。发布于 2019-12-02 16:12Microsoft SQL Server数据库数据库技术赞同 11添加评论分享喜欢收藏申请
MDX 是什么? | MDX中文文档 | MDX中文网
是什么? | MDX中文文档 | MDX中文网Skip to navigation中文文档 / MDX 是什么?5-7 minutes readBy John Otander, Titus WormerMDX 是什么?本文解释了 MDX 格式是什么。 它展示了如何让 markdown、JSX、JavaScript 表达式以及 ESM 中 import 和 export 语句在 MDX 中和平共处。 参见 § 入门 章节以了解如何将 MDX 集成进你的 项目中。目录PrerequisitesMarkdown for the component eraMDX syntaxMarkdownJSXExpressionsESMInterleavingFurther reading预备知识To write and enjoy MDX, you should be familiar with both markdown (see this cheat sheet and tutorial for help) and JavaScript (specifically JSX).组件时代的 markdownMDX 赋予你在 markdown 内容当中使用 JSX 的能力。 你可以导入(import)如见,例如交互式图标或警告框,并将它们嵌入 到你所书写的内容当中。 这让利用组件来编写较长的内容成为了一场革命。 实际上,MDX 可以看作是一种融合了 markdown 和 JSX 的格式,就像下面这个示例:MDX# Hello, world!> Some notable things in a block quote!
标题和块引用是 markdown 格式,而那些 类似 HTML 标签 的是 JSX 格式。 对于诸如强调或标题之类的常见内容,markdown 通常感觉比 HTML 或 JSX 在书写上更自然 更自然。 JSX 是对 JavaScript 的扩展,它 看起来 像 HTML,但是更便于 使用组件(或可重用的东西)。这个实例在 <div> 上使用了 className 属性。 这是因为它是为 React 编写的,并且 React 要求将 class 书写为 className 形式。 其他框架,例如 Vue 和 Preact,则接受 class 形式。 因此,请注意 JSX 在书写上的这些不同, 因为这取决于所用的工具。MDX 还支持 JavaScript 中的一些功能: 花括号中可以使用表达式 ({1 + 1}) ,以及对 ESM (import 和 export) 标准的支持。MDX 语法Note: You don’t have to use this syntax with @mdx-js/* packages. Or use it always. If you’re using a bundler integration you can change between MDX and markdown through the file extension (.mdx vs. .md). Alternatively, options.format can be used.MDX 的语法融合了 markdown 和 JSX。 This gives us something along the lines of literate programming. It also gives us an odd mix of two languages: markdown is whitespace sensitive and forgiving (what you type may not exactly work but it won’t crash) whereas JavaScript is whitespace insensitive and unforgiving (it does crash on typos).Weirdly enough we quite like how they combine!MarkdownMarkdown often feels more natural to type than HTML or JSX for common things like emphasis or headings. Markdown typically looks more like what’s intended and is terser. Instead of the following HTML:HTML
A blockquote with some emphasis.
You can write the equivalent in markdown (or MDX) like so:Markdown> A blockquote with *some* emphasis.
MDX supports standard markdown by default (CommonMark):Markdown# Heading (rank 1)
## Heading 2
### 3
#### 4
##### 5
###### 6
> Block quote
* Unordered
* List
1. Ordered
2. List
A paragraph, introducing a thematic break:
---
```js
some.code()
```
a [link](https://example.com), an ![image](./image.png), some *emphasis*,
something **strong**, and finally a little `code()`.
Nonstandard markdown features (such as GFM, frontmatter, math, syntax highlighting) can be enabled with plugins (see ¶ Using plugins).Some markdown features don’t work in MDX:Indented code does not work in MDX:MDX console.log(1) // this is a paragraph in MDX!
The reason for that is so you can nicely indent your components:MDX
# Hello!
Autolinks do not work in MDX. The reason is that they can be indistinguishable from JSX (for example: Hello, Venus!
Hello, Mars!
…to JSX (or MDX) like this:MDX
JSX is good for components. It makes repeating things more clear and allows for separation of concerns. MDX supports JSX syntax. The following looks a lot like HTML:MDX
Heading!
HTML is a lovely language.
And here is *markdown* in **JSX**!
But as previously mentioned you can use components too. Note that components must be defined. You can import them, define them locally, or pass them in later (see § Using MDX):MDX
You can also use objects with components, such as the `thisOne` component on
the `myComponents` object:
open x={1} label={'this is a string, *not* markdown!'} icon={ /> There are a few edge cases where MDX differs from JSX.ExpressionsMDX also supports JavaScript expressions inside curly braces:MDXTwo is: {Math.PI * 2} Expressions can contain whole JavaScript programs as long as they’re (wrapped in) an expression that evaluates to something that can be rendered. You can use an IIFE like so:MDX{(function () { const guess = Math.random() if (guess > 0.66) { return Look at us. } if (guess > 0.33) { return Who would have guessed?! } return Not me. })()} Expressions can be empty or contain just a comment:MDX{/* A comment! */} ESMMDX supports import and export statements from JavaScript as well. These ESM features can be used within MDX to define things:MDXimport {External} from './some/place.js' export const Local = props => An ESM can also be used for non-components (data):MDXimport {Chart} from './chart.js' import population from './population.js' export const pi = 3.14 InterleavingYou can use markdown “inlines” but not “blocks” inside JSX if the text and tags are on the same line:MDX
Text and tags on one line don’t produce blocks so they don’t produce
s either. On separate lines, they do:MDX
This is a `p`.
We differentiate using this rule (same line or not). Not based on semantics of elements in HTML. So you can build incorrect HTML (which you shouldn’t):MDX
Don’t do this: it’s a `p` in an `h1`
Do this: an `h1` with `code`
It’s not possible to wrap “blocks” if text and tags are on the same line but the corresponding tags are on different lines:MDXWelcome!
This is home of...
# The Falcons!
That’s because to parse markdown, we first have to divide it into “blocks”. So in this case two paragraphs and a heading. Leaving an opening a tag in the first paragraph and a stray closing a tag in the heading.Further readingIf you want to use MDX in your project, see § Getting startedIf you’re getting errors when working with the format, see § Troubleshooting MDX下一页:入门Found a typo? Other suggestions?Edit this page on GitHubPublished on August 11, 2018Modified on January 6, 2023MDX is made with ❤️ in Boise, Amsterdam, and around the This site does not track you.MIT © 2017-2024冀ICP备14002930号-9Project on GitHubSite on GitHubUpdates on TwitterUpdates as RSS feedSponsor on OpenCollective友链BootstrapTailwind CSSReactStyleXNext.jsDocusaurusnpmYarnpnpmBabelWebpackRollupParcelesbuildSvelteAlpine.jsMarkdownSassWebAssemblyPrettierDenoKoaLodashStrapiAxiosNunjucksPugMobXReduxJSDocSkip to content中文文档MDX 是什么?入门Using MDXExtending MDXTroubleshooting MDX使用指南GitHub flavored markdown (GFM)FrontmatterMathSyntax highlightingEmbedMDX on demand核心软件包@mdx-js/esbuild@mdx-js/loader@mdx-js/mdx@mdx-js/node-loader@mdx-js/preact@mdx-js/react@mdx-js/registerremark-mdx@mdx-js/rollup@mdx-js/vue组件在线练习场社区SupportContributeSponsorAboutProjects博客英文官网GitHubTwitterOpenCollect
入门 | MDX 中文网
MDX 中文网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快速开始英:Quick start打包器英:BundlerJSX编辑英:Editor类型英:Types安全英:Security集成英:Integrations打包者英:Bundlers构建系统英:Build systems编译器英:Compilers站点生成器英:Site generatorsJSX 运行时英:JSX runtimesJavaScript 引擎英:JavaScript engines进一步阅读英:Further reading先决条件英:PrerequisitesMDX 依赖于 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打包器英:BundlerMDX 是一种编译为 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:如果你使用 esbuild,请安装并配置 @mdx-js/esbuild英:if you use esbuild, install and configure @mdx-js/esbuild如果你使用 Rollup(或 Vite),请安装并配置 @mdx-js/rollup英:if you use Rollup (or Vite), install and configure @mdx-js/rollup如果你使用 webpack(或 Next.js),请安装并配置 @mdx-js/loader英:if you use webpack (or Next.js), install and configure @mdx-js/loader你还可以在没有打包程序的情况下使用 MDX:英:You can also use MDX without bundlers:你可以使用 @mdx-js/node-loader 在 Node.js 中导入 MDX 文件英:you can import MDX files in Node.js with @mdx-js/node-loader你可以使用我们的核心编译器 @mdx-js/mdx 来编译 MDX 文件英:you can use our core compiler @mdx-js/mdx to compile MDX files你可以使用我们的核心编译器 @mdx-js/mdx 到 evaluate(编译并运行)MDX 文件英:you can use our core compiler @mdx-js/mdx to evaluate (compile and run) MDX files有关这些工具的更多信息,请参阅其专用部分:¶ 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.如果你使用 React,这是默认的;可选择安装和配置 @mdx-js/react英:if you use React, that’s the default; optionally install and configure @mdx-js/react如果使用 Preact,请将 jsxImportSource 于 ProcessorOptions 设置为 'preact';可选择安装和配置 @mdx-js/preact英:if you use Preact, set jsxImportSource in ProcessorOptions to 'preact'; optionally install and configure @mdx-js/preact如果你使用 Svelte,请安装 svelte-jsx,并将 jsxImportSource 于 ProcessorOptions 设置为 'svelte-jsx'英:if you use Svelte, install svelte-jsx, and set jsxImportSource in ProcessorOptions to 'svelte-jsx'如果使用 Vue,请将 jsxImportSource 于 ProcessorOptions 设置为 'vue';可选择安装和配置 @mdx-js/vue英:if you use Vue, set jsxImportSource in ProcessorOptions to 'vue'; optionally install and configure @mdx-js/vue如果使用 Solid,请将 jsxImportSource 于 ProcessorOptions 设置为 'solid-js/h'英:if you use Solid, set jsxImportSource in ProcessorOptions to 'solid-js/h'如果你使用 Emotion,请将 jsxImportSource 于 ProcessorOptions 设置为 '@emotion/react'英:if you use Emotion, set jsxImportSource in ProcessorOptions to '@emotion/react'如果你使用主题 UI,请安装并配置 @mdx-js/react,然后将 MDX 内容封装在…TypeScript should automatically pick it up:example.jsimport 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.tsimport type {MDXComponents} from 'mdx/types.js'
安全英:SecurityMDX 是一种编程语言。如果你信任你的作者,那很好。如果不这样做,那就不安全。英:MDX is a programming language. If you trust your authors, that’s fine. If you don’t, it’s unsafe.不要让互联网上的随机人员编写 MDX。如果你这样做,你可能想考虑将
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.RollupExpand examplerollup.config.jsimport 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.WebpackExpand examplewebpack.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 systemsViteExpand examplevite.config.jsimport 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.编译器英:CompilersBabelExpand plugin and sample useThis plugin:plugin.jsimport 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.jsimport 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 generatorsAstroAstro 有自己的 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.DocusaurusDocusaurus 默认支持 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.GatsbyGatsby 有自己的插件来支持 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.jsExpand examplenext.config.jsimport 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.ParcelParcel 有自己的插件来支持 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 runtimesEmotionExpand exampleexample.jsimport {compile} from '@mdx-js/mdx'
const js = String(await compile('# hi', {jsxImportSource: '@emotion/react', /* otherOptions… */}))
当 jsxImportSource 于 ProcessorOptions 设置为 '@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.InkExpand exampleexample.mdx# Hi!
example.jsimport 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:Shellnode --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.PreactExpand exampleexample.jsimport {compile} from '@mdx-js/mdx'
const js = String(await compile('# hi', {jsxImportSource: 'preact', /* otherOptions… */}))
当 jsxImportSource 于 ProcessorOptions 设置为 '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 UIExpand exampleExample w/o @mdx-js/reactexample.jsimport {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.
Example w/ @mdx-js/reactexample.jsimport {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.
主题界面 是一个特定于 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.SvelteExpand exampleexample.jsimport {compile} from '@mdx-js/mdx'
const js = String(await compile('# hi', {jsxImportSource: 'svelte-jsx', /* otherOptions… */}))
当 jsxImportSource 于 ProcessorOptions 设置为 '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.VueExpand exampleexample.jsimport {compile} from '@mdx-js/mdx'
const js = String(await compile('# hi', {jsxImportSource: 'vue', /* otherOptions… */}))
当 jsxImportSource 于 ProcessorOptions 设置为 '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.SolidExpand exampleexample.jsimport {compile} from '@mdx-js/mdx'
const js = String(await compile('# hi', {jsxImportSource: 'solid-js/h', /* otherOptions… */}))
当 jsxImportSource 于 ProcessorOptions 设置为 '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 enginesNode.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 内容,请参阅 § 使用 MDX英:If you want to use MDX content in your project, see § Using MDX如果你在集成 MDX 时遇到错误,请参阅 § MDX 故障排除 或 § 支持英:If you’re getting errors integrating MDX, see § Troubleshooting MDX or § Support上一章:什么是 MDX?下一章:使用 MDXMDX 中文网 - 粤ICP备13048890号Skip to contentMDX开发文档什么是 MDX?入门使用 MDX扩展 MDXMDX 故障排除学习指南GitHub 风格的 Markdown (GFM)Frontmatter数学语法高亮嵌入MDX 按需注入组件软件包@mdx-js/esbuild@mdx-js/loader@mdx-js/mdx@mdx-js/node-loader@mdx-js/preact@mdx-js/react@mdx-js/rollup@mdx-js/vueremark-mdx组件列表当前版本 v
使用 MDX | MDX 中文网
DX | MDX 中文网Skip to navigation使用 MDX英:Using MDX本文介绍如何在项目中使用 MDX 文件。它展示了如何传递 props 以及如何导入、定义或传递组件。 请参阅 § 入门 了解如何将 MDX 集成到你的项目中。要了解 MDX 格式的工作原理,我们建议你从 § 什么是 MDX 开始。英:This article explains how to use MDX files in your project. It shows how you can pass props and how to import, define, or pass components. See § Getting started for how to integrate MDX into your project. To understand how the MDX format works, we recommend that you start with § What is MDX.内容英:ContentsMDX 的工作原理英:How MDX worksMDX 内容英:MDX content属性英:Props组件列表英:Components布局英:LayoutMDX 提供商英:MDX providerMDX 的工作原理英:How MDX works集成将 MDX 语法编译为 JavaScript。假设我们有一个 MDX 文档 example.mdx:英:An integration compiles MDX syntax to JavaScript. Say we have an MDX document, example.mdx:input.mdxexport function Thing() {return <>World>
}
# Hello
大致变成了下面的 JavaScript。以下内容可能有助于形成心理模型:英:That’s roughly turned into the following JavaScript. The below might help to form a mental model:output-outline.jsx/* @jsxRuntime automatic */
/* @jsxImportSource react */
export function Thing() {
return <>World>
}
export default function MDXContent() {
return
Hello
}
一些观察结果:英:Some observations:输出是序列化的 JavaScript,仍需要评估英:The output is serialized JavaScript that still needs to be evaluated注入注释来配置 JSX 的处理方式英:A comment is injected to configure how JSX is handled这是一个包含导入/导出的完整文件英:It’s a complete file with import/exports导出组件 (MDXContent)英:A component (MDXContent) is exported实际输出是:英:The actual output is:output-actual.jsimport {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs} from 'react/jsx-runtime'
export function Thing() {
return _jsx(_Fragment, {children: 'World'})
}
function _createMdxContent(props) {
const _components = {h1: 'h1', ...props.components}
return _jsxs(_components.h1, {children: ['Hello ', _jsx(Thing, {})]})
}
export default function MDXContent(props = {}) {
const {wrapper: MDXLayout} = props.components || {}
return MDXLayout
? _jsx(MDXLayout, {...props, children: _jsx(_createMdxContent, {...props})})
: _createMdxContent(props)
}
更多观察结果:英:Some more observations:JSX 被编译为函数调用和 React 的导入†英:JSX is compiled away to function calls and an import of React†内容组件可以给 {components: {wrapper: MyLayout}} 来封装所有内容英:The content component can be given {components: {wrapper: MyLayout}} to wrap all content内容组件可以指定 {components: {h1: MyComponent}} 以使用其他内容作为标题英:The content component can be given {components: {h1: MyComponent}} to use something else for the heading† MDX 未与 React 耦合。你还可以将其与 Preact、Vue、Emotion、主题界面 等一起使用。支持经典和自动 JSX 运行时。英:† MDX is not coupled to React. You can also use it with Preact, Vue, Emotion, Theme UI, etc. Both the classic and automatic JSX runtimes are supported.MDX 内容英:MDX content我们刚刚看到 MDX 文件被编译为组件。你可以像你选择的框架中的任何其他组件一样使用这些组件。获取这个文件:英:We just saw that MDX files are compiled to components. You can use those components like any other component in your framework of choice. Take this file:example.mdx# Hi!
它可以在 React 应用中导入和使用,如下所示:英:It could be imported and used in a React app like so:example.jsimport React from 'react'
import ReactDom from 'react-dom'
import Example from './example.mdx' // Assumes an integration is used to compile MDX -> JS.
const root = ReactDom.createRoot(document.getElementById('root'))
root.render(
主要内容作为默认导出导出。所有其他值也会被导出。举个例子:英:The main content is exported as the default export. All other values are also exported. Take this example:example.mdxexport function Thing() {
return <>World>
}
# Hello
可以通过以下方式导入:英:It could be imported in the following ways:example.js// A namespace import to get everything:
import * as everything from './example.mdx' // Assumes an integration is used to compile MDX -> JS.
console.log(everything) // {Thing: [Function: Thing], default: [Function: MDXContent]}
// Default export shortcut and a named import specifier:
import Content, {Thing} from './example.mdx'
console.log(Content) // [Function: MDXContent]
console.log(Thing) // [Function: Thing]
// Import specifier with another local name:
import {Thing as AnotherName} from './example.mdx'
console.log(AnotherName) // [Function: Thing]
属性英:Props在 § 什么是 MDX 中,我们展示了大括号内的 JavaScript 表达式可以在 MDX 中使用:英:In § What is MDX, we showed that JavaScript expressions, inside curly braces, can be used in MDX:example.mdximport {year} from './data.js'
export const name = 'world'
# Hello {name.toUpperCase()}
The current year is {year}
数据也可以传递到 MDXContent,而不是在 MDX 中导入或定义数据。传递的数据称为 props。举个例子:英:Instead of importing or defining data within MDX, data can also be passed to MDXContent. The passed data is called props. Take for example:example.mdx# Hello {props.name.toUpperCase()}
The current year is {props.year}
该文件可以用作:英:This file could be used as:example.jsximport Example from './example.mdx' // Assumes an integration is used to compile MDX -> JS.
// Use a `createElement` call:
React.createElement(Example, {name: 'Venus', year: 2021})
// Use JSX:
组件列表英:Components有一个特殊的属性:components。它需要一个将组件名称映射到组件的对象。举个例子:英:There is one special prop: components. It takes an object mapping component names to components. Take this example:example.mdx# Hello *
它可以从 JavaScript 导入并传递组件,如下所示:英:It can be imported from JavaScript and passed components like so:example.jsximport Example from './example.mdx' // Assumes an integration is used to compile MDX -> JS.
components={{ Planet() { return Pluto } }} /> 你不必传递组件。你还可以在 MDX 中定义或导入它们:英:You don’t have to pass components. You can also define or import them within MDX:example.mdximport {Box, Heading} from 'rebass' MDX using imported components! 由于 MDX 文件是组件,因此它们也可以相互导入:英:Because MDX files are components, they can also import each other:example.mdximport License from './license.md' // Assumes an integration is used to compile MDX -> JS. import Contributing from './docs/contributing.mdx' # Hello world --- 以下是传递组件的其他一些示例:英:Here are some other examples of passing components:example.jsx components={{ // Map `h1` (`# heading`) to use `h2`s. h1: 'h2', // Rewrite `em`s (`*like so*`) to `i` with a goldenrod foreground color. em(props) { return }, // Pass a layout (using the special `'wrapper'` key). wrapper({components, ...rest}) { return }, // Pass a component. Planet() { return 'Neptune' }, // This nested component can be used as ` theme: { text(props) { return } } }} /> 可以在 components 中传递以下键:英:The following keys can be passed in components:使用 Markdown 编写的内容的 HTML 等效项,例如 h1 对应 # heading(有关示例,请参阅 § 组件表)英:HTML equivalents for the things you write with markdown such as h1 for # heading (see § Table of components for examples)wrapper,定义布局(但本地布局优先)英:wrapper, which defines the layout (but a local layout takes precedence)* 对于你使用 JSX 编写的内容来说,任何其他有效的 JavaScript 标识符(foo、Quote、_、$x、a1)(例如 return } All the things. 布局也可以使用 export … from 导入然后导出:英:The layout can also be imported and then exported with an export … from:MDXexport {Layout as default} from './components.js' 布局也可以作为 components.wrapper 传递(但本地布局优先)。英:The layout can also be passed as components.wrapper (but a local one takes precedence).MDX 提供商英:MDX provider你可能不需要提供者。传递组件通常没问题。提供商通常只会增加额外的重量。以这个文件为例:英:You probably don’t need a provider. Passing components is typically fine. Providers often only add extra weight. Take for example this file:post.mdx# Hello world 像这样使用:英:Used like so:app.jsximport React from 'react' import ReactDom from 'react-dom' import {Heading, /* … */ Table} from './components/index.js' import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS. const components = { h1: Heading.H1, // … table: Table } const root = ReactDom.createRoot(document.getElementById('root')) root.render( 有效,这些组件已被使用。英:That works, those components are used.但是,当你嵌套 MDX 文件(将它们相互导入)时,它可能会变得很麻烦。就像这样:英:But when you’re nesting MDX files (importing them into each other) it can become cumbersome. Like so:post.mdximport License from './license.md' // Assumes an integration is used to compile MDX -> JS. import Contributing from './docs/contributing.mdx' # Hello world --- 为了解决这个问题,可以在 React、Preact 和 Vue 中使用 context。Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递 props。像这样设置:英:To solve this, a context can be used in React, Preact, and Vue. Context provides a way to pass data through the component tree without having to pass props down manually at every level. Set it up like so:安装 @mdx-js/react、@mdx-js/preact 或 @mdx-js/vue,具体取决于你使用的框架英:Install either @mdx-js/react, @mdx-js/preact, or @mdx-js/vue, depending on what framework you’re using配置 MDX 集成,并将 providerImportSource 于 ProcessorOptions 设置为该包,因此 '@mdx-js/react'、'@mdx-js/preact' 或 '@mdx-js/vue'英:Configure your MDX integration with providerImportSource in ProcessorOptions set to that package, so either '@mdx-js/react', '@mdx-js/preact', or '@mdx-js/vue'从该包导入 MDXProvider。使用它来封装最顶层的 MDX 内容组件,并将其传递给你的 components:英:Import MDXProvider from that package. Use it to wrap your top-most MDX content component and pass it your components instead:Diff+import {MDXProvider} from '@mdx-js/react' import React from 'react' import ReactDom from 'react-dom' import {Heading, /* … */ Table} from './components/index.js' import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS. const components = { h1: Heading.H1, // … table: Table } const root = ReactDom.createRoot(document.getElementById('root')) -root.render( +root.render( + + + +) 现在你可以删除显式且详细的组件传递:英:Now you can remove the explicit and verbose component passing:Diff import License from './license.md' // Assumes an integration is used to compile MDX -> JS. import Contributing from './docs/contributing.mdx' # Hello world - + --- - + 当 MDXProvider 嵌套时,它们的组件会合并。举个例子:英:When MDXProviders are nested, their components are merged. Take this example:TypeScript<> > …这导致 h1 使用 Component1,h2 使用 Component3,h3 使用 Component4。英:…which results in h1s using Component1, h2s using Component3, and h3s using Component4.要以不同方式合并或根本不合并,请将函数传递给 components。它给出了当前上下文 components,并且将使用它返回的内容。在此示例中,当前上下文组件被丢弃:英:To merge differently or not at all, pass a function to components. It’s given the current context components and what it returns will be used instead. In this example the current context components are discarded:TypeScript<> components={ function () { return {h2: Component3, h3: Component4} } } > > …这导致 h2 使用 Component3,h3 使用 Component4。h1 未使用任何组件。英:…which results in h2s using Component3 and h3s using Component4. No component is used for h1.如果你不嵌套 MDX 文件,或者不经常嵌套它们,请不要使用提供程序:显式传递组件。英:If you’re not nesting MDX files, or not nesting them often, don’t use providers: pass components explicitly.上一章:入门下一章:扩展 MDXMDX 中文网 - 粤ICP备13048890号Skip to contentMDX开发文档什么是 MDX?入门使用 MDX扩展 MDXMDX 故障排除学习指南GitHub 风格的 Markdown (GFM)Frontmatter数学语法高亮嵌入MDX 按需注入组件软件包@mdx-js/esbuild@mdx-js/loader@mdx-js/mdx@mdx-js/node-loader@mdx-js/preact@mdx-js/react@mdx-js/rollup@mdx-js/vueremark-mdx组件列表当前版本 v …TypeScript should automatically pick it up:example.jsimport Post from './post.mdx' // `Post` is now typed. 我们提供的所有 API 都是支持 TypeScript 类型定义的。To enable types for imported .mdx, .md, etcetera files, you should make sure the TypeScript JSX namespace is typed. This is done by installing and using the types of your framework, such as @types/react. Then you can install and use @types/mdx, which adds types to import statements of supported files.You can also import several types about the API of MDX files from @types/mdx. For example:example.tsimport type {MDXComponents} from 'mdx/types.js' 安全性请牢记,MDX 是一门编程语言。 如果你相信你的用户,那就岁月静好。 但是一定要当心用户输入的内容,不要让任何人 上传 MDX 内容。 如果您确有需要,请同时使用 import mdx from '@mdx-js/esbuild' await esbuild.build({ entryPoints: ['index.mdx'], outfile: 'output.js', format: 'esm', plugins: [mdx({/* jsxImportSource: …, otherOptions… */})] }) We support esbuild. Install and configure the esbuild plugin @mdx-js/esbuild. This plugin has an additional option allowDangerousRemoteMdx. Configure your JSX runtime depending on which one you use (React, Preact, Vue, etc.).If you use more modern JavaScript features than what your users support, configure esbuild’s target.RollupExpand examplerollup.config.jsimport mdx from '@mdx-js/rollup' import {babel} from '@rollup/plugin-babel' export default { // … 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… }) ] } 我们提供了对 Rollup 的支持。 您只需安装并配置 Rollup 插件 @mdx-js/rollup 即可。 此插件还有两个额外的参数 include、exclude。 对 JSX 运行时的配置 取决于你所使用的是哪个(React、Preact、 Vue 或其他)如果你所使用的 JavaScript 语法太新,你的用户所用的环境可能不支持, 那么你需要 安装并配置 @rollup/plugin-babel。另请参见 ¶ Vite 和 ¶ WMR (底层使用的是 Rollup) 以了解更多信息。WebpackExpand examplewebpack.config.jsmodule.exports = { module: { // … rules: [ // … { test: /\.mdx?$/, use: [ // `babel-loader` is optional: {loader: 'babel-loader', options: {}}, { loader: '@mdx-js/loader', /** @type {import('@mdx-js/loader').Options} */ options: {/* jsxImportSource: …, otherOptions… */} } ] } ] } } 我们提供了对 webpack 的支持。 你只需要安装并配置 webpack 加载器(loader) @mdx-js/loader 即可。 对 JSX 运行时的配置 取决于你所使用的是哪个(React、Preact、 Vue 或其他)。如果你所使用的 JavaScript 语法太新,你的用户所用的环境可能不支持, 那么你需要 安装并配置 babel-loader。另请参见 ¶ Create React App (CRA)、¶ Next.js 以及 ¶ Vue CLI (底层使用的是 webpack)以了解更多信息。构建系统SnowpackSnowpack 有自己的插件来支持 MDX。 请参阅 snowpack-plugin-mdx 以了解如何将 MDX 于 Snowpack 一起使用。ViteExpand examplevite.config.jsimport {defineConfig} from 'vite' import mdx from '@mdx-js/rollup' export default defineConfig({ plugins: [ mdx(/* jsxImportSource: …, otherOptions… */) ] }) Vite 支持直接在 vite.config.js 文件中的 plugins 参数中配置 Rollup 插件。安装并配置 Rollup 插件 @mdx-js/rollup。如果你所使用的 JavaScript 语法太新,你的用户所用的环境可能不支持, 请配置 Vite 的 build.target 参数。Note: Vite 3 requires the older rollup@2. Make sure rollup@3 is not installed.Note: If you also use vitejs/vite-plugin-react, you need to force @mdx-js/rollup to run in the pre phase before it:vite.config.js// … export default defineConfig({ plugins: [ {enforce: 'pre', ...mdx(/* jsxImportSource: …, otherOptions… */)}, react() ] }) // … 另请参见 ¶ Rollup (Vite 使用的就是 Rollup)以及 ¶ Vue 以了解 更多信息。Vue CLIExpand examplevue.config.jsmodule.exports = { chainWebpack: config => { config.module .rule('mdx') .test(/\.mdx?$/) .use('babel-loader') .loader('babel-loader') .options({plugins: ['@vue/babel-plugin-jsx'], /* Other options… */}) .end() .use('@mdx-js/loader') .loader('@mdx-js/loader') .options({jsx: true, /* otherOptions… */}) .end() } } Vue CLI 目前处于 beta 阶段,版本号是 5,其支持 在 vue.config.js 文件中的 configureWebpack.plugins 参数中直接配置 webpack 的加载器(loaders)。安装并配置 webpack 加载器(loader) @mdx-js/loader。 您还需要配置 Vue 和 Babel 。See also ¶ webpack, which is used in Vue CLI, and see ¶ Vue, which you’re likely using, for more info.Note: to support ESM in vue.config.js or vue.config.mjs, you currently have to use their v5.0.0-rc. See v5.0.0-beta.0 in their changelog for more info. Their latest beta release is currently v5.0.0-rc.2.WMRExpand examplewmr.config.mjsimport {defineConfig} from 'wmr' import mdx from '@mdx-js/rollup' export default defineConfig({ plugins: [ mdx({/* jsxImportSource: …, otherOptions… */}) ] }) WMR supports Rollup plugins directly by adding them to plugins in wmr.config.mjs.Install and configure the Rollup plugin @mdx-js/rollup.See also ¶ Rollup, which is used in WMR, and see ¶ Preact, if you’re using that, for more info.编译器BabelExpand plugin and sample useThis plugin:plugin.jsimport path from 'node:path' import parser from '@babel/parser' import estreeToBabel from 'estree-to-babel' import {compileSync} from '@mdx-js/mdx' 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(path.extname(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() { Object.assign(this, {Compiler: estreeToBabel}) } Can be used like so with the Babel API:example.jsimport 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]}) You should probably use webpack or Rollup instead of Babel directly as that gives the neatest interface. It is possible to use @mdx-js/mdx in Babel and it’s fast, because it skips @mdx-js/mdx serialization and Babel parsing, if Babel is used anyway.Babel does not support syntax extensions to its parser (it has “syntax” plugins but those in fact turn certain 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 generatorsAstroAstro has their own MDX integration. You can add the integration with the Astro CLI (recommended):Shellnpx astro add mdx This base setup allows you to import markdown, Astro components, and other MDX files as components. To use components from frameworks in your MDX files, see Astro’s Framework components guide.For more on how to combine Astro and MDX, see their MDX integration docs.Create React App (CRA)Note: it’s currently probably not a good idea to use CRA.Note: rewiring with CRACO is currently required for CRA 5, due to a bug in react-scripts (facebook/create-react-app#12166), which is also tracked at mdx-js/mdx#1870.Note: warnings about CRACO having incorrect peer dependency "react-scripts@^4.0.0" can currently be ignored.Expand examplesrc/content.mdx# Hello, world! This is **markdown** with JSX: MDX! src/App.jsx/* eslint-disable import/no-webpack-loader-syntax */ import Content from '!@mdx-js/loader!./content.mdx' export default function App() { return } Expand CRACO examplecraco.config.jsconst {addAfterLoader, loaderByName} = require('@craco/craco') module.exports = { webpack: { configure(webpackConfig) { addAfterLoader(webpackConfig, loaderByName('babel-loader'), { test: /\.mdx?$/, loader: require.resolve('@mdx-js/loader') }) return webpackConfig } } } src/App.jsximport Content from './content.mdx' export default function App() { return } CRA supports webpack loaders through webpack loader syntax in imports.Install the webpack loader @mdx-js/loader.For importing MDX without the !@mdx-js/loader! prefix, you can add the loader to the webpack config, by rewiring react-scripts using CRACO.See also ¶ Webpack, which is used in CRA, and see ¶ React, which you’re likely using, for more info.DocusaurusDocusaurus supports MDX by default. See MDX and React on their website for more on how to use MDX with Docusaurus.GatsbyGatsby has their own plugin to support MDX. See gatsby-plugin-mdx on how to use MDX with Gatsby.Next.jsExpand examplenext.config.jsimport nextMdx from '@next/mdx' const withMdx = nextMdx({ // By default only the .mdx extension is supported. extension: /\.mdx?$/, options: {/* providerImportSource: …, otherOptions… */} }) export default withMdx({ // Support MDX files as pages: pageExtensions: ['md', 'mdx', 'tsx', 'ts', 'jsx', 'js'], }) Next.js has its own package to support MDX.Install and configure @next/mdx. There is no need to configure your JSX runtime as React is already set up.The MDX provider can be configured in pages/_app.js. In order to use it, you need to configure the providerImportSource as well.Expand provider examplenext.config.jsimport nextMdx from '@next/mdx' const withMdx = nextMdx({ // By default only the .mdx extension is supported. extension: /\.mdx?$/, options: {providerImportSource: '@mdx-js/react', /* otherOptions… */} }) export default withMdx({ // Support MDX files as pages: pageExtensions: ['md', 'mdx', 'tsx', 'ts', 'jsx', 'js'], }) pages/_app.jsimport {MDXProvider} from '@mdx-js/react' import {Header} from '../components/Header.js' const components = { h1: Header } export default function App({Component, pageProps}) { return ( ) } See Using MDX with Next.js for more details.ParcelParcel 2 has their own plugin to support MDX. See @parcel/transformer-mdx on how to use MDX with Parcel.RazzleRazzle has their own plugin to support MDX. See razzle-plugin-mdx on how to use MDX with Razzle.React StaticReact Static has their own plugin to support MDX. See react-static-plugin-mdx on how to use MDX with React Static.JSX runtimesEmotionExpand exampleexample.jsimport {compile} from '@mdx-js/mdx' const js = String(await compile('# hi', {jsxImportSource: '@emotion/react', /* otherOptions… */})) Emotion is supported when options.jsxImportSource is set to '@emotion/react'. You can optionally install and configure @mdx-js/react, which allows for context based component passing.See also ¶ React, which is used in Emotion, and see ¶ Rollup and ¶ webpack, if you’re using them, for more info.InkExpand exampleexample.mdx# Hi! example.jsimport React from 'react' import {render, Text} from 'ink' import Content from './example.mdx' // Assumes an integration is used to compile MDX -> JS. const components = { h1(props) { return React.createElement(Text, {bold: true, ...props}) }, p: Text } render(React.createElement(Content, {components})) Can be used with:Shellnode --experimental-loader=@mdx-js/node-loader example.js Ink uses the React JSX runtime, so set that up. You will also want to swap HTML elements out for Ink’s components. See § Table of components for what those are and Ink’s documentation on what you can replace them with.See also ¶ React and ¶ Node.js, which you’re using, for more info.PreactExpand exampleexample.jsimport {compile} from '@mdx-js/mdx' const js = String(await compile('# hi', {jsxImportSource: 'preact', /* otherOptions… */})) Preact is supported when options.jsxImportSource is set to 'preact'. You can optionally install and configure @mdx-js/preact, which allows for context based component passing.See also ¶ esbuild, ¶ Rollup, and ¶ webpack, which you might be using, for more info.ReactReact is supported right out of the box. You can optionally install and configure @mdx-js/react, which allows for context based component passing.See also ¶ esbuild, ¶ Rollup, and ¶ webpack, which you might be using, for more info.Experiment: while currently in alpha and not shipping soon, React server components will work with MDX too. There is an experimental demo. And our website is made with them!Theme UIExpand exampleExample w/o @mdx-js/reactexample.jsimport {base} from '@theme-ui/preset-base' import {components, ThemeProvider} from 'theme-ui' import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS. Example w/ @mdx-js/reactexample.jsimport {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. Theme UI is a React-specific library that requires using context to access its effective components. You can optionally install and configure @mdx-js/react, which allows for context based component passing.See also ¶ Emotion, ¶ React, ¶ esbuild, ¶ Rollup, and ¶ webpack, which you might be using, for more info.SvelteExpand exampleexample.jsimport {compile} from '@mdx-js/mdx' const js = String(await compile('# hi', {jsxImportSource: 'svelte-jsx', /* otherOptions… */})) Svelte is supported when options.jsxImportSource is set to 'svelte-jsx', which is a small package that adds support for the JSX automatic runtime to Svelte.See also ¶ esbuild, ¶ Rollup, and ¶ webpack, which you might be using, for more info.VueExpand exampleexample.jsimport {compile} from '@mdx-js/mdx' import babel from '@babel/core' const jsx = String(await compile('# hi', {jsx: true, /* otherOptions… */})) const js = (await babel.transformAsync(jsx, {plugins: ['@vue/babel-plugin-jsx']})).code Vue 3 is supported when using their custom Babel JSX transformer (@vue/babel-plugin-jsx) and configuring @mdx-js/mdx, @mdx-js/rollup, or @mdx-js/loader with jsx: true. You can optionally install and configure @mdx-js/vue, which allows for context based component passing.See also ¶ Vite and ¶ Vue CLI, which you might be using, for more info.SolidExpand exampleexample.jsimport {compile} from '@mdx-js/mdx' const js = String(await compile('# hi', {jsxImportSource: 'solid-js/h', /* otherOptions… */})) Solid is supported when options.jsxImportSource is set to 'solid-js/h'.See also ¶ Vite and ¶ Rollup which you might be using, for more info.JavaScript enginesNode.jsMDX files can be imported in Node by using @mdx-js/node-loader (strongly recommended) or alternatively they can be required with the legacy package @mdx-js/register. See their readmes on how to configure them.Further readingIf you want to use MDX content in your project, see § Using MDXIf you’re getting errors integrating MDX, see § Troubleshooting MDX or § Support上一页:MDX 是什么?下一页:Using MDXFound a typo? Other suggestions?Edit this page on GitHubPublished on October 5, 2021Modified on December 14, 2022MDX is made with ❤️ in Boise, Amsterdam, and around the This site does not track you.MIT © 2017-2024冀ICP备14002930号-9Project on GitHubSite on GitHubUpdates on TwitterUpdates as RSS feedSponsor on OpenCollective友链BootstrapTailwind CSSReactStyleXNext.jsDocusaurusnpmYarnpnpmBabelWebpackRollupParcelesbuildSvelteAlpine.jsMarkdownSassWebAssemblyPrettierDenoKoaLodashStrapiAxiosNunjucksPugMobXReduxJSDocSkip to content中文文档MDX 是什么?入门Using MDXExtending MDXTroubleshooting MDX使用指南GitHub flavored markdown (GFM)FrontmatterMathSyntax highlightingEmbedMDX on demand核心软件包@mdx-js/esbuild@mdx-js/loader@mdx-js/mdx@mdx-js/node-loader@mdx-js/preact@mdx-js/react@mdx-js/registerremark-mdx@mdx-js/rollup@mdx-js/vue组件在线练习场社区SupportContributeSponsorAboutProjects博客英文官网GitHubTwitterOpenCollect MDX 让 Markdown 步入组件时代 - 掘金 首页 首页 沸点 课程 直播 活动 竞赛 商城 APP 插件 搜索历史 清空 创作者中心 写文章 发沸点 写笔记 写代码 草稿箱 创作灵感 查看更多 会员 登录 注册 MDX 让 Markdown 步入组件时代 狂奔滴小马 VIP.5 如鱼得水 2022-02-25 5,491 「这是我参与 2022 首次更文挑战的第 13 天,活动详情查看:2022 首次更文挑战」。 前言 在 MDX 出现之前,将 JSX 与 Markdown 混合书写时,Markdown 的优势就不存在了。 通常采是用基于模板字符串的方式,因此就需要大量的转义和繁琐的语法。 MDX 试图让书写 Markdown 和 JSX 更简单、更具有表现力。当你将组件 (甚至可以是动态的或需要加载数据的组件)与 Markdown 混合书写时,你将写出更有趣的内容。 MDX 是什么 MDX 是一种书写格式,允许你在 Markdown 文档中无缝地插入 JSX 代码。 你还可以导入(import)组件,例如交互式图表或弹框,并将它们嵌入到内容当中。 前提条件 您应该熟悉 markdown 语法和 JavaScript 语法 (特别是 JSX)。 MDX 示例 比如官网的一个例子,如下代码 import {Chart} from './snowfall.js' export const year = 2018 # Last year’s snowfall In {year}, the snowfall was above average. It was followed by a warm spring which caused flood conditions in many of the nearby rivers. 展示效果 如何使用 在 create-react-app 中 只需要安装 @mdx-js/loader, create-react-app@5 支持自定义 loader,代码示例如下 src/App.jsx /* eslint-disable import/no-webpack-loader-syntax */ import Content from "!@mdx-js/loader!./content.mdx"; export default function App() { return } src/content.mdx # Hello, world! This is **markdown** with JSX: MDX! 如果是 webpack 项目只需要加一个 @mdx-js/loader 就可以支持 module.exports = { module: { // … rules: [ // … { test: /\.mdx?$/, use: [ // `babel-loader` is optional: { loader: "babel-loader", options: {} }, { loader: "@mdx-js/loader", /** @type {import('@mdx-js/loader').Options} */ options: { /* jsxImportSource: …, otherOptions… */ }, }, ], }, ], }, }; 插件支持 MDX 也支持插件配置,也就是原先的 markdown 插件 比如要让 markdown 支持表格和 checkboxList ,可以使用 remark-gfm 插件 比如要让 markdown 支持数学公式 可以使用 rehype-katex 插件 在的 option 可以传入参数,代码如下: import rehypeKatex from 'rehype-katex' import remarkMath from 'remark-math' module.exports = { module: { // … rules: [ // … { test: /\.mdx?$/, use: [ // `babel-loader` is optional: {loader: 'babel-loader', options: {}}, { loader: '@mdx-js/loader', /** @type {import('@mdx-js/loader').Options} */ options: {remarkPlugins: [remarkGfm], rehypePlugins: [rehypeKatex]}} } ] } ] } } 当然也可以支持自定义插件,比如 img 要加上默认样式,限制其最大宽度,href 跳转要改成新窗口打开等 ,详情可以查看 unifiedjs.com 定义组件 在支持了 mdx 之后, 可以给 mdx 定义组件, 比如给 H1 传递默认样式等,或者加入默认组件,例如 beta.reactjs.org/ 就加入了很多自定义组件,代码示例如下: import React from "react"; import ReactDom from "react-dom"; import Post from "./post.mdx"; // Assumes an integration is used export const H1 = ({ className, ...props }: HeadingProps) => ( className={cn(className, "text-5xl font-bold leading-tight")} {...props} /> ); const components = { h1: H1, }; ReactDom.render( document.querySelector("#root") ); MDX provider 每个文档都要传 components 很麻烦? 我们可以在最外层导入 MDXProvider,提供 components,组件就可以了。 import React from 'react' import ReactDom from 'react-dom' import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS. import {Heading, /* … */ Table} from './components/index.js' +import {MDXProvider} from '@mdx-js/react' const components = { h1: Heading.H1, // … table: Table } ReactDom.render( - + + + , document.querySelector('#root') ) 在线运行 以上实例都是在构建时运行,那么能到让 MDX 在浏览器运行呢,比如未来,博客的编辑器支持 MDX, 那么我们的博客文章页面就可以有更多交互了。 比如数据通过服务端返回,下面代码是 next.js 示例 import { useState, useEffect, Fragment } from "react"; import * as runtime from "react/jsx-runtime.js"; import { compile, run } from "@mdx-js/mdx"; export default function Page({ code }) { const [mdxModule, setMdxModule] = useState(); const Content = mdxModule ? mdxModule.default : Fragment; useEffect(() => { (async () => { setMdxModule(await run(code, runtime)); })(); }, [code]); return } export async function getStaticProps() { const code = String( await compile("# hi", { outputFormat: "function-body" /* …otherOptions */ }) ); return { props: { code } }; } 实时运行 列如官方的 palyground,就可以实时运行,左边写代码,右侧展示文档 最简单的代码如下 import { VFile } from "vfile"; import { evaluate, } from "@mdx-js/mdx"; const value='## header' const file = new VFile({ basename: "example.mdx", value }); const {default:Result}=await evaluate(file, runtime); 这个 Result 就是一个react 组件,如要实现相似功能可以参考官方 github 中的 editor.client.js。 小结 Markdown 所有程序员都爱,Markdown 在标准化、结构化、组件化都存在硬伤,有了 MDX ,Markdown 有了富交互、内容形态的编写,希望 MDX 尽早尽快更多的投入到的互联网产品中,也希望 MDX 的解析也来越标准化。 推荐阅读 精读《对 Markdown 的思考》 以上就是本文全部内容,希望这篇文章对大家有所帮助,也可以参考我往期的文章或者在评论区交流你的想法和心得,欢迎一起探索前端。 狂奔滴小马 前端公众号 @JS酷 106 文章 785k 阅读 1.4k 粉丝 目录 收起 前言 MDX 是什么 前提条件 MDX 示例 如何使用 插件支持 定义组件 MDX provider 在线运行 实时运行 小结 友情链接: sublime text3 jslint vscode建立java项目 修罗战神狂婿 把我和他写进故事里英语 都市第一医仙 永恒高塔修罗叶白 入门 | MDX中文文档 | MDX中文网
MDX中文文档 | MDX中文网Skip to navigation中文文档 / 入门6-9 minutes readBy Titus Wormer入门本文讲解了如何将 MDX 集成到您的项目中。 还展示了如何将 MDX 与您所使用的打包工具(bundler)和 JSX 运行时协同使用。 如需了解 MDX 格式的工作原理,我们建议您先去阅读 § MDX 是什么 章节。 当您已经设置并准备好使用 MDX 时,请参考 § 使用 MDX 章节。目录PrerequisitesQuick startBundlerJSXEditorTypesSecurityIntegrationsBundlersBuild systemsCompilersSite generatorsJSX runtimesJavaScript enginesFurther reading事先准备MDX 依赖于 JSX,因此您的项目也得是支持 JSX 的。 任何 JSX 运行时(React、Preact、Vue 等)都可以。 注意,我们真的是把 JSX 编译成 JavaScript 了,因此您不必再做相关设置了。所有 @mdx-js/* 匹配的软件包都是使用最新的 JavaScript 语法编写的。 您需要安装的 Node.js 版可以是 12.20、14.14、16.0 或 更新版本。 我们提供的软件包全是支持 ESM 格式 的,因此你必须使用 import 而不是 require。快速开始打包工具(Bundler)MDX 是一种编译成 JavaScript 的语言。 (我们还将普通的 markdown 也编译为 JavaScript。) 最简单的入门方法就是使用一个针对您所使用的打包工具的The easiest way to get started is to use an integration for your bundler if you have one:如果你使用的是 esbuild, 请安装并配置 @mdx-js/esbuild如果你使用的是 Rollup (或集成了 Rollup 的 Vite 或者 WMR), 请安装并配置 @mdx-js/rollup如果你使用的是 webpack (或集成了 webpack 的 Create React App (CRA)、Next.js 或 Vue CLI), 请安装并配置 @mdx-js/loader如果你不使用打包工具(bundler),也可以使用 MDX:如果你想直接在 Node.js 平台上导入(import) MDX 文件,你可以 安装并配置 @mdx-js/node-loader或者,你可以安装并使用 MDX 的核心编译器 @mdx-js/mdx 来手动编译 MDX 文件最后,你还可以通过使用 @mdx-js/mdx 提供的 evaluate 函数, 在任何地方编译 并运行 MDX。有关上述工具的更多信息,请参见各自的专门文档: ¶ Create React App (CRA), ¶ esbuild, ¶ Next.js, ¶ Node.js, ¶ Rollup, ¶ Vite, ¶ Vue CLI, ¶ WMR, ¶ webpack.除了官方提供的集成,还有来自于社区的。 由于我们刚刚进入 v2 版本,以下列表可能在 v2文档中已经过时了。 参见: ¶ Docusaurus, ¶ Gatsby, ¶ Parcel, ¶ Razzle, ¶ React Static 和 ¶ Snowpack。JSX现在,您已经设置了一个集成 MDX 的打包工具或直接使用 @mdx-js/mdx 本体,是时候配置 您的 JSX 运行时了。如果你使用的是 React。 你无需做任何配置。 可以选择性地安装并配置 @mdx-js/react如果你使用的是 Preact, 请将 options.jsxImportSource 设置为 'preact'。 可以选择性地安装并配置 @mdx-js/preact如果你使用的是 Svelte, 请安装 svelte-jsx。 并将 options.jsxImportSource 设置为 'svelte-jsx'。如果你使用的是 Vue 3, 请将 options.jsx 设置为 true。 然后将 Babel 与你的 MDX 集成工具一起使用( webpack 和 Rollup 可以,esbuild 不行)并将其配置为使用 @vue/babel-plugin-jsx。 可以选择性地安装并配置 @mdx-js/vue如果你使用的是 Emotion。 请将 options.jsxImportSource 设置为 '@emotion/react'如果你使用的是 Theme UI, 请安装并配置 @mdx-js/react。 然后将 MDX 内容包括在 学习指南 | MDX 中文网
| MDX 中文网Skip to navigation学习指南英:Guides这些指南解释了如何围绕 MDX 完成几个常见用例和模式。英:These guides explain how to accomplish several common use cases and patterns around MDX.GitHub 风格的 Markdown (GFM)英:GitHub flavored markdown (GFM)本指南探讨如何支持 GFM 功能,例如自动链接字面量、脚注、删除线、表格和任务列表。Frontmatter本指南探讨如何在 MDX 中支持 YAML frontmatter。数学英:Math本指南探讨如何在 MDX 中支持数学 (LaTeX)。语法高亮英:Syntax highlighting本指南探讨如何将语法高亮应用于代码块。嵌入英:Embed本指南探讨了如何在 Markdown 中嵌入推文、要点或代码笔等内容。MDX 按需英:MDX on demand本指南介绍如何使用 @mdx-js/mdx 在服务器上编译 MDX 并在客户端上运行结果。注入组件英:Injecting components本指南展示了如何在 MDX 运行时将任意组件注入到 MDX 中。上一章:开发文档下一章:软件包MDX 中文网 - 粤ICP备13048890号Skip to contentMDX开发文档什么是 MDX?入门使用 MDX扩展 MDXMDX 故障排除学习指南GitHub 风格的 Markdown (GFM)Frontmatter数学语法高亮嵌入MDX 按需注入组件软件包@mdx-js/esbuild@mdx-js/loader@mdx-js/mdx@mdx-js/node-loader@mdx-js/preact@mdx-js/react@mdx-js/rollup@mdx-js/vueremark-mdx组件列表当前版本 v使用指南 | MDX中文文档 | MDX中文网
| MDX中文文档 | MDX中文网Skip to navigation7-11 minutes readBy MDX Contributors使用指南这些使用指南讲解了如何利用 MDX 来解决常见的需求和固定模式。GitHub flavored markdown (GFM)This guide explores how to support GFM features such as autolink literals, footnotes, strikethrough, tables, and task lists.FrontmatterThis guide explores how to support YAML frontmatter in MDX.MathThis guide explores how to support math (LaTeX) in MDX.Syntax highlightingThis guide explores how to apply syntax highlighting to code blocks.EmbedThis guide explores how to embed things like tweets, gists or codepens in markdown.MDX on demandThis guide shows how to use @mdx-js/mdx to compile MDX on the server and run the result on clients.上一页:中文文档下一页:核心软件包Found a typo? Other suggestions?Edit this page on GitHubPublished on November 1, 2021Modified on November 1, 2021MDX is made with ❤️ in Boise, Amsterdam, and around the This site does not track you.MIT © 2017-2024冀ICP备14002930号-9Project on GitHubSite on GitHubUpdates on TwitterUpdates as RSS feedSponsor on OpenCollective友链BootstrapTailwind CSSReactStyleXNext.jsDocusaurusnpmYarnpnpmBabelWebpackRollupParcelesbuildSvelteAlpine.jsMarkdownSassWebAssemblyPrettierDenoKoaLodashStrapiAxiosNunjucksPugMobXReduxJSDocSkip to content中文文档MDX 是什么?入门Using MDXExtending MDXTroubleshooting MDX使用指南GitHub flavored markdown (GFM)FrontmatterMathSyntax highlightingEmbedMDX on demand核心软件包@mdx-js/esbuild@mdx-js/loader@mdx-js/mdx@mdx-js/node-loader@mdx-js/preact@mdx-js/react@mdx-js/registerremark-mdx@mdx-js/rollup@mdx-js/vue组件在线练习场社区SupportContributeSponsorAboutProjects博客英文官网GitHubTwitterOpenCollectMDX 让 Markdown 步入组件时代 - 掘金