question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

gatsby-transformer-remark excerpt is not available in @andrew-codes/gatsby-plugin-elasticlunr-search

See original GitHub issue

Summary

Im trying to use the gatsby-plugin-elasticlunr-search to search through markdown files processed by the gatsby-transformer-remark plugin. When building my index all keys resolve but the excerpt key. Its value is always a blank string. But when I query the markdown files in page the experts have been generated. Are the excerpts generated after the gatsby-config.js is ran or am I running into a valid error?

Relevant information

Example Markdown Page:

---
title: "Bacnet Device"
date: "2018-06-18"
author: "Jacob Evans"
tags: ["bacnet", "device"]
video: "DjXG2Ol7K2o"
---

[Bacnet](http://www.bacnet.org/) is awesome.

BACnet is a communications protocol for Building Automation and Control (BAC) networks that leverage the ASHRAE, ANSI, and ISO 16484-5 standard protocol.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur commodo lectus eget lacus vulputate tempus. Donec lacinia varius eros eu dictum. Morbi non tortor ipsum. Morbi tempus est tellus, quis ultrices urna tempor at. Cras sed eros euismod, cursus metus sed, placerat velit. Aenean in vestibulum quam, non tincidunt nulla. Donec pretium ac magna et hendrerit. Phasellus justo justo, tincidunt id purus eget, sollicitudin pulvinar tellus. Duis eget massa id dui lacinia tempor. Nam elementum nisi non nisi interdum interdum. Maecenas mi velit, suscipit nec lectus ut, pellentesque eleifend nisi. Aliquam a aliquet urna. Mauris volutpat tristique ex sit amet interdum. Duis vitae nibh nec erat egestas vehicula dignissim vel lectus. Morbi fermentum massa in mi auctor fermentum. Nullam rutrum pretium consequat.

gatsby-config.js:

module.exports = {
  siteMetadata: {
    title: 'Example Project',
    slogan: 'Some Slogan',
    company: 'Company Name',
    companyUrl: 'jacobtheevans.com',
  },
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: 'src',
        path: `${__dirname}/src/`
      }
    },
    {
      resolve: `gatsby-plugin-node-fields`,
      options: {
        descriptors: [
          {
            predicate: (node) => node.frontmatter,
            fields: [
              {
                name: 'video',
                getter: node => node.frontmatter.video,
                defaultValue: ''
              }
            ]
          }
        ]
      }
    },
    {
      resolve: `gatsby-plugin-google-fonts`,
      options: {
        fonts: [
          `roboto`,
          'roboto-slab'
        ]
      }
    },
    'gatsby-plugin-react-helmet',
    'gatsby-transformer-remark',
    {
      resolve: `@andrew-codes/gatsby-plugin-elasticlunr-search`,
      options: {
        fields: ['title', 'tags', 'slug', 'author', 'date', 'excerpt'],
        resolvers: {
          MarkdownRemark: {
            excerpt: node => {
              console.log(node) // prints out blank string
              return node.excerpt
            },
            title: node => node.frontmatter.title,
            tags: node => node.frontmatter.tags,
            slug: node => node.fields.slug,
            author: node => node.frontmatter.author,
            date: node => node.frontmatter.date
          }
        }
      }
    }
  ]
}

Environment

  System:
    OS: Linux 4.16 Fedora 27 (Workstation Edition) 27 (Workstation Edition)
    CPU: x64 Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
    Shell: 4.4.23 - /bin/bash
  Binaries:
    Node: 8.11.2 - /usr/bin/node
    Yarn: 1.7.0 - /usr/bin/yarn
    npm: 5.6.0 - /usr/bin/npm
  Browsers:
    Firefox: 60.0.2
  npmPackages:
    gatsby: ^1.9.247 => 1.9.273 
    gatsby-link: ^1.6.40 => 1.6.45 
    gatsby-plugin-google-fonts: ^0.0.4 => 0.0.4 
    gatsby-plugin-node-fields: ^0.0.6 => 0.0.6 
    gatsby-plugin-react-helmet: ^2.0.10 => 2.0.11 
    gatsby-source-filesystem: ^1.5.39 => 1.5.39 
    gatsby-transformer-remark: ^1.7.44 => 1.7.44 

File contents (if changed)

package.json:

{
  "name": "example-project",
  "description": "Learning and trying",
  "version": "1.0.0",
  "author": "Jacob Evans",
  "dependencies": {
    "@andrew-codes/gatsby-plugin-elasticlunr-search": "^1.0.4",
    "elasticlunr": "0.9.5",
    "gatsby": "^1.9.247",
    "gatsby-link": "^1.6.40",
    "gatsby-plugin-google-fonts": "^0.0.4",
    "gatsby-plugin-node-fields": "^0.0.6",
    "gatsby-plugin-react-helmet": "^2.0.10",
    "gatsby-source-filesystem": "^1.5.39",
    "gatsby-transformer-remark": "^1.7.44",
    "react-fontawesome": "^1.6.1",
    "react-helmet": "^5.2.0",
    "react-redux": "^5.0.7",
    "react-youtube": "^7.6.0",
    "redux": "^4.0.0",
    "styled-components": "^3.3.2"
  },
  "license": "MIT",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write 'src/**/*.js'",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "prettier": "^1.12.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/gatsbyjs/gatsby-starter-default"
  }
}

gatsby-node.js:

const { createFilePath } = require(`gatsby-source-filesystem`)
const path = require('path')

exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
  const { createNodeField } = boundActionCreators
  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode, basePath: 'pages' })
    createNodeField({
      node,
      value,
      name: 'slug'
    })
  }
}

exports.createPages = async ({ graphql, boundActionCreators }) => {
  const { createPage } = boundActionCreators
  const result = await graphql(`
  {
    allMarkdownRemark {
      edges {
        node {
          fields {
            slug
          }
        }
      }
    }
  }
  `)
  if (result.errors) throw result.errors
  for (let edge of result.data.allMarkdownRemark.edges) {
    const { node } = edge
    createPage({
      path: node.fields.slug,
      component: path.resolve('./src/templates/blog-post.js'),
      context: {
        slug: node.fields.slug
      }
    })
  }
}

gatsby-browser.js:

import React from 'react'
import { Router } from 'react-router-dom'
import { Provider } from 'react-redux'

import store from './src/redux'

export const replaceRouterComponent = ({ history }) => {
  const ConnectedRouterWrapper = ({ children }) => (
    <Provider store={store}>
      <Router history={history}>{children}</Router>
    </Provider>
  )
  return ConnectedRouterWrapper
}

gatsby-ssr.js:


import React from 'react'
import { Provider } from 'react-redux'
import { renderToString } from 'react-dom/server'

import { store } from './src/redux'

export const replaceRenderer = ({ bodyComponent, replaceBodyHTMLString }) => {
  const ConnectedBody = () => (
    <Provider store={store}>
      {bodyComponent}
    </Provider>
    )
  replaceBodyHTMLString(renderToString(<ConnectedBody />))
}

Please let me know if there is any other information I can provide to help debug this.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:3
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

5reactions
JacobTheEvanscommented, Jul 2, 2018

Just in case anyone body wants an easier solution in the future to deal with this. I looked into the source code of the gatsby-transformer-remark and just ported the way there were making excerpts into the actual resolver like so.

gatsby-config.js:

const remark = require('remark')
const visit = require('unist-util-visit')

module.exports = {
  siteMetadata: {
    title: 'Example Project',
    slogan: 'Your slogan',
  },
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: 'src',
        path: `${__dirname}/src/`
      }
    },
    {
      resolve: `gatsby-plugin-node-fields`,
      options: {
        descriptors: [
          {
            predicate: (node) => node.frontmatter,
            fields: [
              {
                name: 'video',
                getter: node => node.frontmatter.video,
                defaultValue: ''
              }
            ]
          }
        ]
      }
    },
    {
      resolve: `gatsby-plugin-google-fonts`,
      options: {
        fonts: [
          `roboto`,
          'roboto-slab'
        ]
      }
    },
    'gatsby-plugin-react-helmet',
    'gatsby-transformer-remark',
    {
      resolve: `@andrew-codes/gatsby-plugin-elasticlunr-search`,
      options: {
        fields: ['title', 'tags', 'slug', 'author', 'date', 'excerpt'],
        resolvers: {
          MarkdownRemark: {
            excerpt: node => {
              const excerptLength = 136 // Hard coded excerpt length
              let excerpt = ''
              const tree = remark().parse(node.rawMarkdownBody)
              visit(tree, 'text', (node) => {
                excerpt += node.value
              })
              return excerpt.slice(0, excerptLength) + '...'
            },
            title: node => node.frontmatter.title,
            tags: node => node.frontmatter.tags,
            slug: node => node.fields.slug,
            author: node => node.frontmatter.author,
            date: node => node.frontmatter.date
          }
        }
      }
    }
  ]
}
3reactions
Tomekmularczykcommented, Apr 15, 2019

Little more elegant solution for creating excerpt from raw markdown:

const remark = require("remark");
const stripMarkdown = require("strip-markdown");

   {
      resolve: "@gatsby-contrib/gatsby-plugin-elasticlunr-search",
      options: {
        fields: ["title", "date", "excerpt"],
        resolvers: {
          MarkdownRemark: {
            title: node => node.frontmatter.title,
            date: node => node.frontmatter.date,
            excerpt: node => {
              const text = remark()
                .use(stripMarkdown)
                .processSync(node.rawMarkdownBody);

              const excerptLength = 140; // Hard coded excerpt length
              return String(text).substring(0, excerptLength) + "...";
            },
          }
        }
      }
   }
Read more comments on GitHub >

github_iconTop Results From Across the Web

gatsby-transformer-remark
This plugin adds additional fields to the MarkdownRemark GraphQL type including html , excerpt , headings , etc. Other Gatsby plugins can also...
Read more >
Using Excerpts - Gatsby
gatsby -transformer-remark allows you to get an excerpt from a markdown post. By default, it will prune the first 140 characters, but you...
Read more >
How to get only a portion of the mdx rendered article with ...
gatsby -transformer-remark exposes an excerpt field that can be truncated to any desired length using pruneLength , which is a piece of the ......
Read more >
Generating excerpts using GatsbyJS Markdown plugins
Learn how to generate excerpts with `gatsby-transformer-remark` and work ... There is no excerpt_separator option available for this plugin.
Read more >
Initial Thoughts On Migrating from gatsby-transformer-remark ...
Until I replaced gatsby-plugin-my-social-cards with gatsby-remark-twitter-cards the plugin body , timeToRead and excerpt were not available ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found