diff --git a/packages/gatsby-plugin-page-creator/src/__tests__/derive-path.ts b/packages/gatsby-plugin-page-creator/src/__tests__/derive-path.ts index bd87e466779da..03127d9d0a5f8 100644 --- a/packages/gatsby-plugin-page-creator/src/__tests__/derive-path.ts +++ b/packages/gatsby-plugin-page-creator/src/__tests__/derive-path.ts @@ -265,6 +265,74 @@ describe(`derive-path`, () => { ).toEqual(`foo/dolores/[...name]`) }) + it(`supports index paths`, () => { + expect( + derivePath( + `{Page.path}`, + { + path: `/`, + }, + reporter + ).derivedPath + ).toEqual(`index`) + expect( + derivePath( + `{Page.path}.js`, + { + path: `/`, + }, + reporter + ).derivedPath + ).toEqual(`index.js`) + expect( + derivePath( + `foo/{Page.path}`, + { + path: `/`, + }, + reporter + ).derivedPath + ).toEqual(`foo`) + expect( + derivePath( + `foo/{Page.path}/bar`, + { + path: `/`, + }, + reporter + ).derivedPath + ).toEqual(`foo/bar`) + expect( + derivePath( + `foo/{Page.pathOne}/{Page.pathTwo}`, + { + pathOne: `/`, + pathTwo: `bar`, + }, + reporter + ).derivedPath + ).toEqual(`foo/bar`) + expect( + derivePath( + `foo/{Page.pathOne}/{Page.pathTwo}`, + { + pathOne: `/`, + pathTwo: `/bar`, + }, + reporter + ).derivedPath + ).toEqual(`foo/bar`) + expect( + derivePath( + `foo/{Page.path}/[...name]`, + { + path: `/`, + }, + reporter + ).derivedPath + ).toEqual(`foo/[...name]`) + }) + it(`handles special chars`, () => { expect( derivePath( diff --git a/packages/gatsby-plugin-page-creator/src/derive-path.ts b/packages/gatsby-plugin-page-creator/src/derive-path.ts index 5487b1e5f04e9..5193358599a32 100644 --- a/packages/gatsby-plugin-page-creator/src/derive-path.ts +++ b/packages/gatsby-plugin-page-creator/src/derive-path.ts @@ -6,9 +6,12 @@ import { extractAllCollectionSegments, switchToPeriodDelimiters, stripTrailingSlash, + removeFileExtension, } from "./path-utils" const doubleForwardSlashes = /\/\/+/g +// Match 0 or 1 of "/" +const indexRoute = /^\/?$/ // Generates the path for the page from the file path // product/{Product.id} => /product/:id, pulls from nodes.id @@ -64,6 +67,14 @@ export function derivePath( // 4. Remove double forward slashes that could occur in the final URL modifiedPath = modifiedPath.replace(doubleForwardSlashes, `/`) + // 5. Remove trailing slashes that could occur in the final URL + modifiedPath = stripTrailingSlash(modifiedPath) + + // 6. If the final URL appears to be an index path, use the "index" file naming convention + if (indexRoute.test(removeFileExtension(modifiedPath))) { + modifiedPath = `index${modifiedPath}` + } + const derivedPath = modifiedPath return {