Skip to content

Instantly share code, notes, and snippets.

@souporserious
Created May 11, 2021 21:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souporserious/b23b787f6d94de5027d82f0932c9c653 to your computer and use it in GitHub Desktop.
Save souporserious/b23b787f6d94de5027d82f0932c9c653 to your computer and use it in GitHub Desktop.
NextJS implementation for docs
export const getStaticPaths: GetStaticPaths = async () => {
const filePaths = await getComponentMDXPaths();
const paths = filePaths.map((filePath) => {
const extension = path.extname(filePath);
const name = path.basename(filePath, extension);
const slug = name.toLowerCase().replace(/\s/g, '-');
return { params: { slug } };
});
return {
paths,
fallback: false,
};
};
export const getStaticProps: GetStaticProps = async ({ params }) => {
const filePaths = await getComponentMDXPaths();
const filePath = filePaths.find((filePath) => {
const extension = path.extname(filePath);
const name = path.basename(filePath, extension);
return name.toLowerCase().replace(/\s/g, '-') === params.slug;
});
const contents = await fs.readFile(path.resolve(filePath), 'utf-8');
const { code, frontmatter } = await bundleMDX(contents, {
cwd: path.dirname(filePath),
});
return {
props: {
code,
frontmatter,
},
};
};
const path = require('path');
const matter = require('gray-matter');
const getRootPath = (filePath) => path.resolve(process.cwd(), 'src', filePath);
module.exports = async function (source) {
const callback = this.async();
const { content, data } = matter(source);
const code = `
import { Doc } from '${getRootPath('components/Doc')}'
export { getDocProps as getStaticProps } from '${getRootPath('utils')}'
export default (props) =>
<Doc
title="${data.title ?? ''}"
lead="${data.lead ?? ''}"
category="${data.category ?? ''}"
updated="${data.updated ?? ''}"
{...props}
/>
${content}
`;
return callback(null, code);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment