Without exception, the name of every Gatsby theme must begin with the prefix gatsby-theme-
. This is to ensure that Gatsby can effectively identify theme packages when it performs build-time compilation.
As we saw from the example of gatsby-theme-blog
, some themes are responsible for scaffolding directories to give guidance to theme users and to house certain important information. It’s often the case that we need to prepare some required directories that will be leveraged by other plugins or that scaffold a required folder, such as the src/pages directory. We can use the onPreBootstrap
lifecycle hook to initialize required directories so builds don’t fail.
In this example, we create a gatsby-node.js file to indicate to Gatsby that for the theme to function properly, we need two directories (Gatsby’s usual src/pages directory as well as a posts directory):
// gatsby-theme-minimal/gatsby-node.js
exports
.
onPreBootstrap
=
({
store
,
reporter
})
=>
{
const
{
program
}
=
store
.
getState
()
const
dirs
=
[
path
.
join
(
program
.
directory
,
"posts"
),
path
.
join
(
program
.
directory
,
"src/pages"
),
]
dirs
.
forEach
(
dir
=>
{
if
(
!
fs
.
existsSync
(
dir
))
{
reporter
.
log
(
`Creating the
${
dir
}
directory`
)
mkdirp
.
sync
(
dir
)
}
})
}
Using Gatsby lifecycle hooks within gatsby-node.js can help you avoid some of the common pitfalls that occur when others try to use your Gatsby theme, especially missing directories that are required for use by the theme. Naming your theme according to Gatsby conventions is also essential for the proper functioning of your theme in arbitrary Gatsby sites.
Leave a Reply