From 8049bf2ec9839b36097e4069aa5400f12f9a0643 Mon Sep 17 00:00:00 2001 From: Julian Date: Tue, 6 Nov 2018 01:08:41 +0100 Subject: [PATCH] fix: adjust page order to make nested matchPaths work (#9719) As per [#9705](https://github.com/gatsbyjs/gatsby/issues/9705), this changes the order of the pages in pages-writer.js in order to account for the matchPath specificity and therefore make "nested" matchPaths work. The proposed fix `sortByNumeric` is the most performant solution I could come up with: [Benchmarks](https://runkit.com/juliansthl/5be08b8f2513440012001807) Thanks a lot to @pieh for all the help! (this is my first PR, please let me know if I have to adjust anything) --- .../src/internal-plugins/query-runner/pages-writer.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/gatsby/src/internal-plugins/query-runner/pages-writer.js b/packages/gatsby/src/internal-plugins/query-runner/pages-writer.js index 1d1e6e80bd58b..0dd7a653cb230 100644 --- a/packages/gatsby/src/internal-plugins/query-runner/pages-writer.js +++ b/packages/gatsby/src/internal-plugins/query-runner/pages-writer.js @@ -36,10 +36,12 @@ const writePages = async () => { }) pagesData = _(pagesData) - // Ensure pages keep the same sorting through builds - // and sort pages with matchPath to end so explicit routes - // will match before general. - .sortBy(p => `${p.matchPath ? 1 : 0}${p.path}`) + // Ensure pages keep the same sorting through builds. + // Pages without matchPath come first, then pages with matchPath, + // where more specific patterns come before less specific patterns. + // This ensures explicit routes will match before general. + // Specificity is inferred from number of path segments. + .sortBy(p => `${p.matchPath ? 9999 - p.matchPath.split(`/`).length : `0000`}${p.path}`) .value() const newHash = crypto .createHash(`md5`)