Skip to content

Sohel Ahmed [Work in progress]

Adding "blog" in URL in Gatsby Theme Minimal Blog by LekoArt

GatsbyJS, Theme, Static site, React, Blog1 min read

This website (https://sohelahmed.site) is using amazing gatsby-starter-minimal-blog by Lekoart. Thanks LekoArts.

By default it comes with blog link without "blog" in URL. Example:

If I create a new blog with slug "my-blog-post" the URL for it will be https://sohelahmed.site/my-blog-post. However I wanted "blog" in the URL https://sohelahmed.site/blog/my-blog-post. So it can be achieved by deleting old posts and creating new with "blog" in the URL in gatsby-node.js

/path/to/project/gatsby-node.js
1const withDefaults = require(`@lekoarts/gatsby-theme-minimal-blog-core/utils/default-options`);
2const postTemplate = require.resolve(
3 `@lekoarts/gatsby-theme-minimal-blog-core/src/templates/post-query.tsx`
4);
5const pageTemplate = require.resolve(
6 `@lekoarts/gatsby-theme-minimal-blog-core/src/templates/page-query.tsx`
7);
8const contactPageTemplate = require.resolve(
9 `./src/@lekoarts/gatsby-theme-minimal-blog-core/templates/contactpage-query.tsx`
10);
11
12exports.onCreatePage = ({ page, actions }, themeOptions) => {
13 const { createPage, deletePage } = actions;
14 const old_page = Object.assign({}, page);
15
16 const { basePath, blogPath, tagsPath, formatString } = withDefaults(
17 themeOptions
18 );
19
20 const compo_path = `${process.cwd()}/node_modules/@lekoarts/gatsby-theme-minimal-blog-core/src/templates/post-query.tsx`;
21 if (page.componentPath === compo_path) {
22 deletePage(old_page);
23 }
24};
25
26exports.createPages = async ({ actions, graphql, reporter }, themeOptions) => {
27 const { createPage } = actions;
28
29 const { basePath, blogPath, tagsPath, formatString } = withDefaults(
30 themeOptions
31 );
32
33 const result = await graphql(`
34 query {
35 allPost(sort: { fields: date, order: DESC }) {
36 nodes {
37 slug
38 }
39 }
40 allPage {
41 nodes {
42 slug
43 }
44 }
45 tags: allPost(sort: { fields: tags___name, order: DESC }) {
46 group(field: tags___name) {
47 fieldValue
48 }
49 }
50 }
51 `);
52
53 if (result.errors) {
54 reporter.panicOnBuild(
55 `There was an error loading your posts or pages`,
56 result.errors
57 );
58 return;
59 }
60
61 const posts = result.data.allPost.nodes;
62
63 posts.forEach((post) => {
64 createPage({
65 path: `/${basePath}/blog/${post.slug}`.replace(/\/\/+/g, `/`),
66 component: postTemplate,
67 context: {
68 slug: post.slug,
69 formatString,
70 },
71 });
72 });
73
74 const pages = result.data.allPage.nodes;
75
76 if (pages.length > 0) {
77 pages.forEach((page) => {
78 createPage({
79 path: `/${basePath}/${page.slug}`.replace(/\/\/+/g, `/`),
80 component:
81 page.slug === "/contact" ? contactPageTemplate : pageTemplate,
82 context: {
83 slug: page.slug,
84 },
85 });
86 });
87 }
88};
© 2020 by Sohel Ahmed [Work in progress]. All rights reserved.
Theme by LekoArts