Mdx: Remove `layoutProps` from transpiled output

Created on 21 Aug 2019  路  4Comments  路  Source: mdx-js/mdx

Since these values are already available in scope since they're exports, we can avoid instantiating the object and passing to MDXLayout.

馃拵 v2

Most helpful comment

I would love this! The layoutProps logic seems to prevent .mdx pages in Next.js from exporting any of the data fetching functions because Next.js at some point removes those export statements, but MDX already included them in layoutProps, which causes a ReferenceError 馃槵

All 4 comments

I would love this! The layoutProps logic seems to prevent .mdx pages in Next.js from exporting any of the data fetching functions because Next.js at some point removes those export statements, but MDX already included them in layoutProps, which causes a ReferenceError 馃槵

For people who stumble upon this and are looking for a quick fix, I wrote a Babel plugin which removes these three functions from layoutProps 馃榿 This is by no means an "official" workaround, I'm only speaking for myself.

// https://nextjs.org/docs/basic-features/data-fetching
const DATA_FETCH_FNS = ['getStaticPaths', 'getStaticProps', 'getServerProps']

module.exports = () => {
  return {
    visitor: {
      ObjectProperty(path) {
        if (
          DATA_FETCH_FNS.includes(path.node.value.name) &&
          path.findParent(
            (path) =>
              path.isVariableDeclarator() &&
              path.node.id.name === 'layoutProps',
          )
        ) {
          path.remove()
        }
      },
    },
  }
}

Copy this into a file and add it to your Babel configuration:

// babel.config.js
module.exports = {
  presets: [
    'next/babel',
  ],
  plugins: [
    './etc/babel-plugin-nextjs-mdx-patch',
  ],
}

I'm using mdx to define pages in Next.js, via its pageExtensions: ['mdx'] option. Currently, I'm setting the page title by including export const title = 'Foo' within a .mdx file, and then using a custom wrapper like this:

import Head from 'next/head';

const Wrapper = ({ children, title }) => (
  <main>
    <Head>
      <title>{title}</title>
    </Head>
    {children}
  </main>
);

This works because the layoutProps are passed to Wrapper as props. If they're removed, is there a different solution that I could use for the same effect?

Closed by #1199 (v2 branch)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

deligent-ant picture deligent-ant  路  3Comments

Exelord picture Exelord  路  4Comments

codebender828 picture codebender828  路  4Comments

riceboyler picture riceboyler  路  3Comments

MatthewCaseres picture MatthewCaseres  路  4Comments