Skip to content

Instantly share code, notes, and snippets.

@souporserious
Last active January 14, 2022 23:40
Show Gist options
  • Save souporserious/f207ee91133b6572b01039b609821b8e to your computer and use it in GitHub Desktop.
Save souporserious/f207ee91133b6572b01039b609821b8e to your computer and use it in GitHub Desktop.
Grab links from a NextJS pages directory using TS Morph
import { Project } from 'ts-morph';
import { capitalCase } from 'case-anything';
const project = new Project();
project.addSourceFilesAtPaths([
`src/pages/**/*{.tsx,.mdx,.json}`,
`!src/pages/_*.tsx`,
`!src/pages/api/*.ts`,
]);
const allLinks = getLinks(project.getDirectory('src/pages'));
function getLinks(directory: Directory, parentSlug?: string) {
const directoryName = directory.getBaseName();
const sourceFiles = directory.getSourceFiles();
const subDirectories = directory
.getDirectories()
.filter(
(directory) =>
!['api', 'assets', 'components', 'hooks', 'utils'].includes(
directory.getBaseName()
)
);
return sourceFiles
.map((sourceFile) => {
const name = sourceFile
.getBaseNameWithoutExtension()
.replace('index', '');
return {
title: capitalCase(
name === '' ? directoryName : sourceFile.getBaseName()
),
slug: `${parentSlug}/${directoryName}/${name}`,
};
})
.concat(
subDirectories.flatMap((directory) =>
getLinks(
directory,
directoryName === 'pages' ? '' : `${parentSlug}/${directoryName}`
)
)
);
}
import { Project } from 'ts-morph';
import { capitalCase } from 'case-anything';
import matter from 'gray-matter';
const project = new Project();
const sourceFiles = project.addSourceFilesAtPaths([
`src/pages/**/*{.tsx,.mdx,.json}`,
`!src/pages/_*.tsx`,
`!src/pages/api/*.ts`,
]);
const allLinks = sourceFiles
.map((sourceFile) => {
let name = sourceFile.getBaseNameWithoutExtension();
if (name.includes('index')) {
name = sourceFile.getDirectory().getBaseName();
}
if (sourceFile.getExtension() === '.mdx') {
const { data } = matter(sourceFile.getText());
name = data.title || name;
}
return {
title: capitalCase(name),
path: sourceFile.getFilePath(),
slug: sourceFile
.getFilePath()
.replace(`${process.cwd()}/src/pages/`, '')
.slice(0, -4),
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment