【问题标题】:How to get exports form mdx in nextjs如何在下一个 js 中从 mdx 获取导出
【发布时间】:2023-01-19 14:06:01
【问题描述】:

我的问题

mdx 上的 nextjs 文档声明它不支持 frontmatter。相反,建议创建一个常量并将其导出 [1]。但是我似乎无法获得以这种方式导出的数据。例如使用以下

/* -- ./pages/example.mdx -- */
export const meta = {
    title: 'some example title'
}
/* -- ./pages/index.js -- */
import Example from './example.mdx';

export default function Index ({ ... props }) {
   return <Example />
}

似乎导入的内容可以用作反应组件,但似乎在任何地方都没有对 meta 属性的引用。

  • Example 没有 meta 属性
  • import { meta } from './example.mdx 不产生任何东西
  • 渲染的组件上没有meta
  • 使用require ('./example.mdx') 产生相同的结果。

我想做什么

我有一个降价文件列表,想创建一个列出所有文件的概览页面,使用每个文件中定义的元数据。类似于以下内容

import fs from 'fs/promises';
import path from 'path';

export async function getStaticProps () {
    const root = path.join (process.cwd (), 'pages/items');
    const listing = await fs.readdir(root);
    const items = listing
        .filter (item => item.endsWith ('.mdx'))
        .map (item => {
            const meta = require (`./items/${item}`).meta;
            const id = item.replace (/\.md$/, '');
            return { id, ... meta }
        });

    return { props: { items } };
}

export default function Overview ({ items, ... props }) {
    /* ... use items */
}

编辑

使用.md.mdx 似乎有很大区别。在我在这里给出的示例中,我使用了.mdx,但在本地我使用了.md。切换扩展使一切正常。

奇怪的是,即使它们都在 next.config.js 中配置,扩展也会产生如此大的差异

const withMDX = require ('@next/mdx') ({
    extension: /\.mdx?$/
});
module.exports = withMDX ({ /* ... */ });

[1] https://nextjs.org/docs/advanced-features/using-mdx#frontmatter

【问题讨论】:

    标签: next.js mdxjs


    【解决方案1】:

    使用.mdx 扩展而不是.md 扩展。

    【讨论】:

      【解决方案2】:

      如果您使用的是打字稿,似乎可以创建一个打字文件来导入它

      第 1 步 - 创建打字文件

      declare module '*.mdx' {
          export const meta: {
              title: string
          }
      }
      

      第 2 步 - 导入导出的内容

      import Example, {meta} from './example.mdx';
      

      从这里得到答案https://gist.github.com/peterblazejewicz/1ac0d99094d1886e7c9aee7e4faddef3#file-index-d-ts-L68

      【讨论】:

        猜你喜欢
        • 2022-01-02
        • 2023-02-23
        • 1970-01-01
        • 2012-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        相关资源
        最近更新 更多