In my Docusaurus website, I want to have a Markdown file stored in one place and displayed in six places. How do I do this (a) in Docusaurus, (b) in HTML (c) a better way?
My attempt:
In srccomponentsMyFile.js:
import React from 'react';
import Content from '../../docs/myFile.md';
const MyFile = () => <Content />;
export default MyFile;
In docsmyFile.md:
Hello world
in docsanotherFile.md:
import MyFile from './myFile.md';
<MyFile />
Result: ‘unexpected error’ during Vercel deploy
Neil Sandy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You can import Markdown content using .mdx
components. There are other ways to do this, but this method is also referenced by the folks at Docusaurus.
You will need to use .mdx
files for this.
Here’s a simple example of how to do this.
Example:
Let’s say you have an “export” file, a file that will not be published to your Docusaurus site but will have its contents reused elsewhere.
NOTE: All files created will go into your /docs folder.
-
Let’s create this file and call it:
_markdown-partial-example.mdx
. The_
filename prefix makes it so that it will not create a doc page for this file. It will not be published. -
Now, let’s create a file that will contain the
_markdown-partial-example.mdx
‘s imported contents. Let’s call that file:someOtherDoc.mdx
-
Populate our reusable content file,
_markdown-partial-example.mdx
:
// ._markdown-partial-example.mdx
------------------------------------------------------------------------------
<span>Hello {props.name}</span>
This is text some content from `_markdown-partial-example.mdx`.
- Now, populate the “import” file,
someOtherDoc.mdx
:
// someOtherDoc.mdx
------------------------------------------------------------------------------
import PartialExample from './_markdown-partial-example.mdx';
<PartialExample name="User" />
Result
You Docusaurus site will create a page for the someOtherDoc.mdx
file and use the contents of imported from _markdown-partial-example.mdx
.
This method is also described in Docusaurus’s docs.
This answer was given to me by a colleague.
The main points are:
-
This works for .mdx files. It may also work for .md files, since I believe Docusaurus treats them both the same, but it is neater and clearer to stick to .mdx.
-
Prepend an underscore character to make Docusaurus ignore a file. For example, _partial.mdx.
-
In the file you want to use (renderable.mdx for example), code like this:
above
“`mdx-code-block
import SomeText from “./_partial.mdx”<SomeText /> ``` below
The contents of the file _partial.mdx will be displayed between ‘above’ and ‘below’.
Because of the underscore character, the partial file will not be displayed on its own; it will only be displayed when it is included in another file, as shown.
Neil Sandy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.