盖茨比乔布斯_盖茨比MDX简介

盖茨比乔布斯

Most of you have probably used Markdown files in your Gatsby.js sites, and you already know it’s an amazing way to write content. But plain Markdown is geared towards text-based content, and it can be limiting when you want to step outside of that use case. That all changes with MDX, a superset of Markdown that allows us to embed JSX directly into Markdown files. Sounds awesome, doesn’t it? In this article we’ll explore the basics of MDX with Gatsby, including some introductory techniques to help you start using it right away.

你们中的大多数人可能在Gatsby.js网站中使用了Markdown文件,并且您已经知道这是一种写内容的绝妙方法。 但是普通的Markdown面向的是基于文本的内容,当您想退出该用例时可能会受到限制。 这一切都随MDX (Markdown的超集)而改变,它使我们能够将JSX直接嵌入Markdown文件中。 听起来很棒,不是吗? 在本文中,我们将探讨Gatsby的MDX基础知识,包括一些入门技术,可帮助您立即开始使用它。

Before we dive in, you will need to have a Gatsby project that is set up and ready to edit. If you need help getting to that point, please follow the steps in Your First Steps with Gatsby v2 and then return here afterwards.

在我们深入之前,您将需要建立一个Gatsby项目并准备进行编辑。 如果您需要帮助,请按照Gatsby v2的“第一步”中的步骤进行操作 ,然后返回此处。

安装 (Installation)

Thanks to Gatsby’s incredible plugins library, the installation process is easy! Using MDX with Gatsby only requires a single plugin, gatsby-plugin-mdx, along with the MDX peer dependencies.

借助Gatsby 令人难以置信的插件库 ,安装过程很容易! 将MDX与Gatsby一起使用仅需要一个插件gatsby-plugin-mdx以及MDX对等项依赖项。

Let’s install those now, like this:

让我们现在安装它们,如下所示:

$ yarn add gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react

Let’s also install gatsby-source-filesystem so that we can make use of frontmatter, generate Gatsby nodes from local files, and use import/export functionality in our MDX files:

让我们还安装gatsby-source-filesystem以便我们可以使用frontmatter,从本地文件生成Gatsby节点,以及在我们的MDX文件中使用导入/导出功能:

$ yarn add gatsby-source-filesystem

While not technically required, this step is highly recommended — as it really opens the full potential of MDX content with Gatsby!

尽管在技术上不是必需的,但我们还是强烈建议您执行此步骤,因为它确实为Gatsby带来了MDX内容的全部潜力!

组态 (Configuration)

Like with all Gatsby plugins, we need to add configuration details to the plugins section of gatsby-config.js.

与所有Gatsby插件一样,我们需要在gatsby-config.jsplugins部分添加配置详细信息。

Let’s configure both gatsby-plugin-mdx and gatsby-source-filesystem like this:

让我们像这样配置gatsby-plugin-mdxgatsby-source-filesystem

gatsby-config.js gatsby-config.js
module.exports = {//...siteMetadata, etcplugins: [{resolve: `gatsby-source-filesystem`,options: {name: `pages`,path: `${__dirname}/src/pages/`,},},{resolve: `gatsby-plugin-mdx`,options: {defaultLayouts: {default: require.resolve(`./src/components/layout.js`),},},// ... other plugins],
}

Notice that we are setting a default key in the defaultLayouts option. This will automatically wrap all MDX files with our site’s default layout.js component.

请注意,我们在defaultLayouts选项中设置了default键。 这将使用我们网站的默认layout.js组件自动包装所有MDX文件。

The gatsby-config.js file has been edited, so don’t forget to restart the development environment before proceeding!

gatsby-config.js文件已被编辑,因此在继续操作之前,请不要忘记重新启动开发环境!

配置选项 (Configuration options)

There are several configuration options available for gatsby-plugin-mdx:

gatsby-plugin-mdx有几个配置选项可用:

  • extensions: (Array of strings) Sets file extensions that will be processed as MDX. I typically set this to ['.mdx', '.md'] to also process normal Markdown files as MDX.

    扩展名:(字符串数组)设置将作为MDX处理的文件扩展名。 我通常将此设置为['.mdx', '.md']以将普通的Markdown文件也处理为MDX。

  • defaultLayouts: (Object) This is frequently used when you have multiple types of generated content, such as blog posts and product reviews. (And as seen above, you can also set a default key to auto-wrap all MDX files.)

    defaultLayouts :(对象)当您具有多种类型的生成内容(例如,博客文章和产品评论)时,通常使用此方法。 (如上所述,您还可以设置default键来自动包装所有MDX文件。)

  • gatsbyRemarkPlugins: (Array of plugin objects) This allows us to use various Gatsby-specific remark plugins along with the MDX processing. The gatsby-remark-images plugin is often used here.

    gatsbyRemarkPlugins :(插件对象数组)这使我们可以将各种特定于Gatsby的备注插件与MDX处理一起使用。 这里经常使用gatsby-remark-images插件。

  • remarkPlugins: (Array of plugin objects) Similar to the above option, but for non-Gatsby dependent remark plugins.

    remarkPlugins:(插件对象的数组)与上述选项类似,但适用于非依赖于Gatsby的备注插件 。

  • rehypePlugins: (Array of plugin objects) Similar to above, but for rehype plugins.

    rehypePlugins:(插件对象数组)与上述类似,但用于rehype插件 。

  • mediaTypes: (Array of strings) Sets which media types are processed. (You probably won’t need to use this very often.)

    mediaTypes:(字符串数组)设置要处理的媒体类型。 (您可能不需要经常使用它。)

Full details on the usage of these options can be found in the plugin’s documentation. These docs are excellent, and I highly recommend going over them after reading this article! 🔍

有关这些选项的用法的完整详细信息,请参见插件的文档 。 这些文档非常出色,强烈建议阅读本文后再仔细阅读! 🔍

基本用法 (Basic Usage)

The configuration we have so far can already process all .mdx files in our site. And thanks to Gatsby’s built-in behavior, if we add them to the src/pages/ directory they will also become pages automatically!

到目前为止,我们所拥有的配置已经可以处理我们站点中的所有.mdx文件。 并且由于Gatsby的内置行为,如果我们将它们添加到src/pages/目录中,它们也将自动成为页面!

Let’s do that now by creating a simple MDX file at src/pages/mdx-intro/index.mdx. We’ll start off with some frontmatter and basic Markdown text, like a typical Markdown blog page would have:

现在,通过在src/pages/mdx-intro/index.mdx创建一个简单的MDX文件来进行src/pages/mdx-intro/index.mdx 。 我们将从一些前沿和基本的Markdown文本开始,例如典型的Markdown博客页面将具有:

/src/pages/mdx-intro/index.mdx /src/pages/mdx-intro/index.mdx
---
title: MDX is Magical!
path: /mdx-intro
date: 2019-08-25
---# Hooray For MDX!This will be like turbo-charged Markdown!

You can view this new page by visiting http://localhost:8000/mdx-intro in your browser.

您可以通过在浏览器中访问http://localhost:8000/mdx-intro来查看此新页面。

You’ll probably recognize this page creation pattern if you went through the Your First Steps with Gatsby v2 article, the only difference being this is an MDX file instead of Markdown. This is nothing special or new so far. Let’s change that!

如果您阅读了《使用Gatsby的第一步》 v2文章,您可能会认识到这种页面创建模式,唯一的区别是这是MDX文件而不是Markdown。 到目前为止,这没什么特别的或新的。 让我们改变它!

在MDX中使用组件 (Using Components in MDX)

One of the primary features of MDX is that we can import and use JSX components right inside of Markdown content.

MDX的主要功能之一是,我们可以在Markdown内容内部导入和使用JSX组件。

To demonstrate this, let’s create a simple component at /src/components/TitleBar.js that will let us display a customized title bar.

为了说明这一点,让我们在/src/components/TitleBar.js中创建一个简单的组件,该组件将显示自定义的标题栏。

/src/components/TitleBar.js /src/components/TitleBar.js
import React from 'react';const TitleBar = ({ text, size, bkgdColor }) => ({margin: '2rem 0',padding: '2rem',backgroundColor: bkgdColor || '#fff',}}>{fontSize: size || '18px',margin: 0,}}>{text}
);export default TitleBar;

Next, let’s update our MDX file to look like this:

接下来,让我们更新我们的MDX文件,如下所示:

/src/pages/mdx-intro/index.mdx /src/pages/mdx-intro/index.mdx
---
title: MDX is Magical!
path: /mdx-intro
date: 2019-08-25
---
import TitleBar from "../../components/TitleBar.js";This will be like turbo-charged Markdown!

There are two things to note here:

这里有两件事要注意:

  • First, we just imported and used a React component directly inside Markdown! Let that sink in for a moment, because this is an incredibly powerful concept. (Imagine blog posts with animated charts and/or dynamically loaded data, complex interactivity, and more.)

    首先,我们只是直接在Markdown内部导入并使用了React组件! 请稍等一下,因为这是一个非常强大的概念。 (想象一下带有动画图表和/或动态加载的数据,复杂的交互性以及更多内容的博客文章。)

  • Second, you may have noticed that we are able to access the frontmatter values from props.pageContext.frontmatter. This can be quite useful, too!

    其次,您可能已经注意到,我们能够从props.pageContext.frontmatter访问frontmatter值。 这也可能非常有用!

Important: If your MDX files contain frontmatter, always place any import statements after the frontmatter block!

重要提示:如果您的MDX文件包含frontmatter,始终将frontmatter块之后的任何import语句!

Go ahead and view the updated page in your browser, and try editing the size and bkgdColor props to watch it update. It’s a really simple example, but again: we are using a React component inside Markdown! Pretty sweet, right?!

继续并在浏览器中查看更新的页面,然后尝试编辑sizebkgdColor道具以观看其更新。 这是一个非常简单的示例,但是再次:我们在Markdown中使用了React组件! 很漂亮吧?

分配布局 (Assigning Layouts)

As mentioned in the configuration section, MDX provides us with an easy way to set up custom layouts. These layouts are convenient for wrapping additional styling and/or content around our MDX files.

如配置部分所述,MDX为我们提供了一种设置自定义布局的简便方法。 这些布局可方便地在我们的MDX文件中包装其他样式和/或内容。

配置默认布局 (Configuring default layouts)

We can set up default layouts for our MDX files in gatsby-config.js, even for specific locations. Take a look at this example:

我们甚至可以在gatsby-config.js为MDX文件设置默认布局,甚至可以为特定位置设置默认布局。 看一下这个例子:

gatsby-config.js gatsby-config.js
module.exports = {plugins: [{resolve: `gatsby-source-filesystem`,options: {name: `pages`,path: `${__dirname}/src/pages/`,},},{resolve: `gatsby-source-filesystem`,options: {name: `posts`,path: `${__dirname}/src/blog/`,},},{resolve: `gatsby-plugin-mdx`,options: {defaultLayouts: {posts: require.resolve("./src/components/blog-layout.js"),default: require.resolve("./src/components/layout.js"),},},},],
}

In this example, we have configured our site so that all MDX files sourced from the /src/blog directory would use blog-layout.js as a layout/wrapper. We also set up a default config here, too.

在此示例中,我们已经配置了站点,以便所有从/src/blog目录获得的MDX文件都将blog-layout.js用作布局/包装器。 我们也在这里也设置了default配置。

Note: This behavior doesn’t currently seem to work as expected with MDX files sourced from the pages directory. (But you can still wrap them with a default layout setting, like we have currently done.)

注意:对于从pages目录获取的MDX文件,此行为当前似乎无法正常工作。 (但是,您仍然可以像我们目前所做的那样使用default布局设置来包装它们。)

手动分配或删除布局 (Manually assigning or removing layouts)

Sometimes you will need to wrap a specific MDX file with a unique layout, or with no layout at all. This can be easily done by using JavaScript’s export default syntax inside our MDX files, which overrides any defaultLayout settings. We’ll cover that in the next section!

有时,您需要使用唯一的布局或完全没有布局来包装特定的MDX文件。 可以通过在我们的MDX文件中使用JavaScript的export default语法轻松完成此操作,该语法会覆盖所有defaultLayout设置。 我们将在下一部分中介绍它!

导入其他MDX文件 (Importing Other MDX Files)

In addition to importing/using JSX components, we can also import and use other MDX files as if they were components. (Hint: they actually are!)

除了导入/使用JSX组件外,我们还可以导入和使用其他MDX文件,就像它们是组件一样。 (提示:它们实际上是!)

Let’s create a new MDX file in our components directory, at /src/components/postSignature.mdx. We will use this at the bottom of our MDX page as an author’s signature.

让我们在/src/components/postSignature.mdx components目录中创建一个新的MDX文件。 我们将在MDX页面底部将其用作作者的签名。

/src/components/postSignature.mdx /src/components/postSignature.mdx
##### Thanks for Reading!*🐊 Al E. Gator | alligator.io | al@example.com*export default ({ children }) => (<>{children}
)

Notice the export default statement at the bottom of the file. As mentioned in the previous section, this is how we can override our defaultLayout configuration settings. In this case, we’re exporting an empty <> wrapper around our signature instead.

请注意文件底部的export default语句。 如上一节所述,这就是我们可以覆盖defaultLayout配置设置的方式。 在这种情况下,我们将在签名周围导出一个空的<>包装器。

Moving along, let’s import this MDX signature into our main MDX file, over at /src/pages/mdx-intro/index.mdx:

/src/pages/mdx-intro/index.mdx ,我们将这个MDX签名导入到/src/pages/mdx-intro/index.mdx主MDX文件中:

/src/pages/mdx-intro/index.mdx /src/pages/mdx-intro/index.mdx
---
title: MDX is Magical!
path: /mdx-intro
date: 2019-08-25
---
import TitleBar from "../../components/TitleBar.js";
import PostSignature from "../../components/postSignature.mdx";This is like turbo-charged Markdown!

You should now see this signature at the bottom of the mdx-intro page. Awesome!! 😎

现在,您应该在mdx-intro页面的底部看到此签名。 太棒了!! 😎

GraphQL查询 (GraphQL Queries)

Thanks to the plugin combo of gatsby-plugin-mdx and gatsby-source-filesystem, our MDX pages are also readily available to us via GraphQL queries.

多亏了gatsby-plugin-mdxgatsby-source-filesystem的插件组合,我们的MDX页面也可以通过GraphQL查询轻松获得。

We won’t spend much time on this, as this functionality is nearly identical to querying plain Markdown files in the same manner. (The only difference is that the MDX nodes are in allMdx and mdx instead of allMarkdownRemark and markdownRemark.)

我们不会花很多时间,因为此功能几乎与以相同方式查询普通Markdown文件相同。 (唯一的区别是MDX节点位于allMdxmdx而不是allMarkdownRemarkmarkdownRemark 。)

Here’s an example query that would fetch the frontmatter of all available MDX files:

这是一个示例查询,它将获取所有可用的MDX文件的最重要信息:

query {allMdx {edges {node {frontmatter {titlepathdate(formatString: "MMMM DD, YYYY")}}}}
}

提供其他数据 (Providing Other Data)

We can also provide additional data through our MDX files by using JavaScript’s export syntax, (not to be confused with export default as used above!) Any exported variables are added to the GraphQL schema automatically, so that we can use it when needed in GraphQL queries and/or during rendering.

我们还可以使用JavaScript的export语法通过MDX文件提供其他数据(不要与上面使用的export default混淆!)任何导出的变量都会自动添加到GraphQL模式中,以便在GraphQL中需要时可以使用它查询和/或渲染期间。

Here’s some example “Food Truck Review” data that we could add to our MDX page:

这是一些示例“ Food Truck Review”数据,我们可以将其添加到MDX页面:

export const myReviews = [{name: "Tim's Tacos",overall: 9,variety: 7,price: 8,taste: 9},{name: "Noodleville",overall: 7,variety: 5,price: 6,taste: 8},{name: "Waffle Shack",overall: 6,variety: 5,price: 4,taste: 6},
];

After adding that anywhere in the file, we could query the data in GraphQL by accessing allMdx.nodes.exports, like this:

将其添加到文件中的任何位置后,我们可以通过访问allMdx.nodes.exports来查询GraphQL中的数据,如下所示:

query MdxExports {allMdx {nodes {exports {myReviews {nameoverallvarietypricetaste}}}}
}

This is just a really basic demo, but this functionality can be used in incredibly creative and dynamic ways.

这只是一个非常基本的演示,但是可以以令人难以置信的创造性和动态方式使用此功能。

一个实际的例子 (A Practical Example)

Let’s finish up by adding a fun & practical example to our page. We’re going to use the myReviews data that we set up above to display an animated bar chart!

最后,我们在页面上添加一个有趣且实用的示例。 我们将使用上面设置的myReviews数据显示动画条形图!

First, let’s add the Recharts library to our site. This is a powerful but lightweight charting library that I use frequently in my client projects.

首先,让我们将图表库添加到我们的网站。 这是我在客户项目中经常使用的功能强大但轻量级的图表库。

$ yarn add recharts

Next, we will use Recharts to create a reusable bar chart component. Since this isn’t an article about Recharts, just go ahead and create a new file at /src/components/BarChart.js and paste in the following code:

接下来,我们将使用“图表”创建可重复使用的条形图组件。 由于这不是关于Recharts的文章,因此只需继续在/src/components/BarChart.js创建一个新文件,然后粘贴以下代码即可:

/src/components/BarChart.js /src/components/BarChart.js
import React, { PureComponent } from 'react';
import {BarChart,Bar,XAxis,YAxis,CartesianGrid,Tooltip,Legend,ResponsiveContainer,
} from 'recharts';const colorsList = ['#008f68', '#6db65b', '#4aae9b', '#dfa612'];class ExampleChart extends PureComponent {render() {return ({ width: '100%', height: 350 }}>{this.props.bars.map((bar, i) => ())});}
}export default ExampleChart;

Now we have a nice bar chart component set up, so we just need to import and use it in the MDX page. Here’s our final version:

现在我们已经建立了一个不错的条形图组件,因此我们只需要在MDX页面中导入并使用它即可。 这是我们的最终版本:

/src/pages/mdx-intro/index.mdx /src/pages/mdx-intro/index.mdx
---
title: MDX is Magical!
path: /mdx-intro
date: 2019-08-25
---import TitleBar from '../../components/TitleBar';
import PostSignature from '../../components/postSignature.mdx';
import BarChart from "../../components/BarChart";export const myReviews = [{name: "Tim's Tacos",overall: 9,variety: 7,price: 8,taste: 9},{name: "Noodleville",overall: 7,variety: 5,price: 6,taste: 8},{name: "Waffle Shack",overall: 6,variety: 5,price: 4,taste: 6},
];This page is built with turbo-charged Markdown!#### My Food Reviews:

You should now see a sweet-looking multi-colored bar chart that animates into view, and even has animated tooltips on rollover. 📊👈

现在,您应该可以看到动画效果逼真的彩色条形图,甚至在过渡时也具有动画化的工具提示。 📊👈

And I’ll say it again:This is all inside a Markdown (MDX) page! Just think of all the interesting blog posts and pages you can create in no time flat…

我再说一遍: 这些都在Markdown(MDX)页面中! 只要想一想您可以立即创建的所有有趣的博客文章和页面……

结论 (Conclusion)

We have really covered a lot in this intro to MDX with Gatsby! Hopefully it wasn’t too overwhelming, and you can see that this combo is a total game-changer for rapid website development.

Gatsby在MDX简介中确实涵盖了很多内容! 希望它并没有太大的影响,您可以看到此组合对于快速的网站开发是完全改变游戏规则的。

However, we only scratched the surface of what is possible. From here, I recommend digging into the Gatsby docs section on MDX. It’s a rabbit-hole worth venturing down, I promise! 🕳🐇

但是,我们只是从表面上摸索了一切。 从这里开始,我建议深入研究MDX上的Gatsby docs部分 。 我保证,这是一个值得冒险的兔子洞! 🕳🐇

翻译自: https://www.digitalocean.com/community/tutorials/gatsbyjs-mdx-in-gatsby

盖茨比乔布斯


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部