1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Create a Data Directory in Gatsby using the onPreBootstrap lifecycle

    Jason LengstorfJason Lengstorf
    gatsbyGatsby
    >=2.13.1

    Learn how to architect the React components in your Gatsby theme to maximize reusability and extendability while minimizing maintenance and hassle.

    The first step is to make sure the data directory exists so because gatsby-source-filesystem will throw an error if it doesn't.

    This lesson will cover that step.

    For a written version of this course, check out the Gatsby docs.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: To create pages, we need to create a file called gatsbynode.js. Inside our Gatsby node, we need to do several things. First, we need to make sure the data directory exists. The reason for that is that when we first fire up our theme, if that data directory doesn't exist, Gatsby's source file system is going to throw an error.

    Second, we need to define the event type. The reason for that is that if we don't have any events to find, we should get an empty array not an error. Once that's done, we need to define resolvers for any custom fields. In this case, we're going to have a slug field.

    Finally, we need to query for events and create pages. Our first step is going to be to make sure the data directory exists. To do this, we're going to use the onPreBootstrap API hook from Gatsby.

    We're going to grab the reporter out to let people know that things are happening. Inside of this, we're going to decide where our content lives. We'll call this content path. This is going to be data. That's the data directory that we created over here.

    Next, we're going to use the FS dependency from Node. This is a built-in. We're just going to get FS by requiring FS. Then we want to check if the content path doesn't exist, we want to create it.

    We'll start by sending out a message. We'll say reporter.info, and we are creating the content path directory. Then we use FS. We're going to use makedersync to create the content path.

    Now whenever we fire up a site using this theme, the first thing that'll happen is it's going to check if the data directory exists, and if not, it'll create it.