-
I've seen similar questions to this without clear replies, so the answer might be "you're doing it wrong" but here's what I am trying to achieve. Given the mdx files in the same directory at the bottom of this post, how can I return an array of their meta data? e.g. [
{ "title": "First", "published": true },
{ "title": "Second", "published": false },
{ "title": "Third", "published": true }
] Why would I want this? I might use this data to show a list of published pages on my site. Approach 1This discussion suggests using a module Approach 2Read the files using const fs = require("fs");
const { join } = require("path");
const remark = require("remark");
const mdx = require("remark-mdx");
const file = fs.readFileSync(join(__dirname, "file1.mdx"), "utf8");
const contents = remark().use(mdx).parse(file);
console.log(contents); outputs the contents, except the meta I want to read!
Please point me in the right direction 😀 Files
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
Hi Mike! This indeed seems to be a question that comes up a lot, so it might be good to answer this once and for ever. But: it does depend a lot on the tools you are using. So maybe this question is more a question for Gatsby, Next, or another framework. We’re comparing two things here: frontmatter and import/exports. Frontmatter is more close to markdown (but not specific to it: many files can have frontmatter. It’s actually more of a preprocessing step, and has more to do with YAML as it supports several “documents” in one file, where the common case is the first one being YAML the rest being arbitrary other data). Import/exports has to do with JS, and relates to what MDX is: it takes an MDX document, and turns it into JavaScript. The output still has to be executed, similar to other JavaScript files. So it depends: is the metadata about your posts static? Or is it dynamic? Does it need to be “in“ files or can it be in a JSON or whatever other data format in a different file? If you’re going with frontmatter, it doesn’t really have anything to do with MDX:
When going with import/exports, it’s a somewhat similar task
|
Beta Was this translation helpful? Give feedback.
Hi Mike! This indeed seems to be a question that comes up a lot, so it might be good to answer this once and for ever.
But: it does depend a lot on the tools you are using. So maybe this question is more a question for Gatsby, Next, or another framework.
And it depends on what you actually want to do, so it might not be possible to have one answer.
We’re comparing two things here: frontmatter and import/exports.
Frontmatter is more close to markdown (but not specific to it: many files can have frontmatter. It’s actually more of a preprocessing step, and has more to do with YAML as it supports several “documents” in one file, where the common case is the first one being YAML the rest being…