Skip to content

Instantly share code, notes, and snippets.

@danielwaltz
Created June 15, 2024 13:14
Show Gist options
  • Save danielwaltz/7585ff1e2d56a1d1f6c0ce7595ca30ea to your computer and use it in GitHub Desktop.
Save danielwaltz/7585ff1e2d56a1d1f6c0ce7595ca30ea to your computer and use it in GitHub Desktop.
Nuxt Logical Page Groups Module (WIP)
import { defineNuxtModule } from 'nuxt/kit';
import type { NuxtPage } from 'nuxt/schema';
const PAGE_GROUP_REGEX = /\(([^)]+)\)/;
export default defineNuxtModule({
meta: {
name: 'page-groups',
},
setup(_options, nuxt) {
const rewritePagePath = (page: NuxtPage, pathPrefix = '') => {
const matchArray = page.path.match(PAGE_GROUP_REGEX);
if (!matchArray) return;
const [routeName] = matchArray;
console.log({
path: page.path,
updatedPath: `${pathPrefix}${page.path.replace(routeName, '')}`,
});
page.path = `${pathPrefix}${page.path.replace(routeName, '')}`;
};
const processPage = (page: NuxtPage, parentPath?: string) => {
rewritePagePath(page, parentPath);
if (page.children) {
for (const childPage of page.children) {
processPage(childPage, page.path);
}
}
};
nuxt.hook('pages:extend', (pages) => {
for (const page of pages) {
processPage(page);
}
});
},
});
@danielwaltz
Copy link
Author

Use by wrapping a page directory in parens. For example account/index.vue becomes (account)/index.vue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment