How to unpublish a gatsby page without deleting it?
Asked Answered
S

4

6

I used a Gatsby starter for my static site, and one of the pages included in that starter is a demo page with all of the UI elements.

I want to keep the page (so I can copy and paste from the demo) but don't want to be publicly available. How do I "unpublish" without deleting the file?

Is there a way to tell gatsby-node.js to skip that page when generating the public facing site?

Sheikdom answered 4/4, 2019 at 15:38 Comment(0)
E
13

There are a bunch of Gatsby Node API helpers that you can use, one being deletePage.

If you have a page src/pages/demo.js, this will delete that page during creation.

// gatsby-node.js
exports.onCreatePage = async ({ page, actions: { deletePage } }) => {
    if (page.path.match(/^\/demo/)) {
      deletePage(page)
    }
}
Etana answered 4/4, 2019 at 18:50 Comment(1)
This was easiest for me, I just added process.env.NODE_ENV === production &&Sheikdom
G
3

Lots of good options here, just wanna throw my hat in the ring for plugin options that prevent pages from being created in the first place:

If it is a page component, i.e inside src/pages folder, gatsby use a plugin called gatsby-plugin-page-creator to generate page, and it recently accept a ignore patterns.

There's a caveat, the built-in gatsby-plugin-page-creator doesn't take user options, so we'd have to rename the pages folder to ignore it.

  root
    └── src
-        └── pages
+        └── screens  <-- rename
               └── index.js
               └── ignore-file-name.js

And then in gatsby-config.js:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-page-creator`,
      options: {
        path: `${__dirname}/src/screens`,
        ignore: [`ignore-file-name.js`],
      },
    },
  ]
}

If it is a programmatically page generated from markdown or json, you might be able to ignore it in gatsby-source-file-system, as pointed out in this github comment.

The example there even ignores file based on environment, which is more useful since you can still see your reference during development, but it won't show in build.

{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/content`,
    ignore: process.env.NODE_ENV === `production` && [`**/draft-*`]
  }
}
Giselle answered 5/4, 2019 at 5:17 Comment(0)
C
2

An alternative would be to add a "published" attribute to the frontmatter assuming it's a markdown page that could be a true or false value. Then add logic into your gatsby-node.js file which looks at this to determine whether or not to run createPage().

Carboxylate answered 4/4, 2019 at 20:9 Comment(0)
R
0

You can also change the file extension to something that does not indicate it is JavaScript, like mypage.js.draft, works for me.

Downside could be that your editor might not automatically detect that it is a JS anymore. (My VSCode still does)

Revere answered 19/3 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.