/gsx2

Primary LanguageVueOtherNOASSERTION

Optimize Contentful Gridsome.js Example Project

This is a Gridsome.js project bootstrapped with gridsome create.

Getting Started

Configure environment variables

  1. Copy .env.example to .env
  2. Setup Contentful variables inside the gridsome.server.js file to match your CMS see example config
  3. Configure your uniform data source

Install Gridsome CLI tool if you don't have

npm install --global @gridsome/cli

Install packages

npm i
# or
yarn

Run the development server

npm run develop
# or
yarn develop

Build for production and launch server

npm run build
# or
yarn build

Example gridsome.server.js

// Server API makes it possible to hook into various parts of Gridsome
// on server-side and add custom data to the GraphQL data layer.
// Learn more: https://gridsome.org/docs/server-api/
const contentful = require('contentful');

// Changes here require a server restart.
// To restart press CTRL + C in terminal and run `gridsome develop`
module.exports = function (api) {
  const client = contentful.createClient({
    space: process.env.CONTENTFUL_SPACE_ID,
    accessToken: process.env.CONTENTFUL_CDA_ACCESS_TOKEN
  });

  api.loadSource(async ({ addCollection, addSchemaResolvers }) => {
    // Use the Data Store API here: https://gridsome.org/docs/data-store-api/    
    const collection = addCollection('Talk');    
    const talk = await client.getEntries({
      content_type: 'talk',
      include: 2
    });
    talk.items.forEach((item) => {      
      collection.addNode({
        sys: { ...item.sys },
        fields: JSON.stringify(item.fields)
      });
    });   
  });

  api.createPages(async ({ createPage }) => {
    // Use the Pages API here: https://gridsome.org/docs/pages-api/)      
    const data = await client.getEntries({
      content_type: 'page',
      include: 2
    });    
    data.items.forEach((item) => {
      createPage({
        path: `${item.fields.slug}`,
        component: './src/templates/ContentfulPage.vue',
        context: {
          title: item.fields.title,
          id: item.fields.slug,
          slug: `${item.fields.slug}`,
          path: `${item.fields.slug}`,
          sys: { ...item.sys },
          fields: { ...item.fields }
        }
      });
    });
  });
}

Learn More

To learn more about Gridsome.js, take a look at the following resources: