Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding an image field (with a relative path) to .md files #1874

Closed
theiliad opened this issue Aug 21, 2017 · 6 comments
Closed

Adding an image field (with a relative path) to .md files #1874

theiliad opened this issue Aug 21, 2017 · 6 comments

Comments

@theiliad
Copy link
Contributor

theiliad commented Aug 21, 2017

  • Gatsby 1.8.12
  • Node v6.10.2
  • MacOS Sierra

=======================

Hey Fellas 😃
I'm pretty new to GraphQL, and markdownRemark is confusing me.

I'm trying to add a field to my .md files like so:

image: "./preview.png"

and I want to be able to use that image in the blog-post react component. (<img src{imageURL} />)

I've tried adding fields and they usually work, except I think Gatsby realizes that this one is pointing to a file and keeps on throwing errors for the graphQL syntax.

image

My query before adding image:

export const pageQuery = graphql`
  query BlogPostByPath($path: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      id
      html
      frontmatter {
        title
        desc
        date(formatString: "MMMM DD, YYYY")
        tags
        author
      }
    }
  }
`

Sample .md file:

---
title:    Networking layers in Swift 3.0
desc:     A salted duck egg is a Chinese preserved food product made by soaking duck eggs in brine, or packing each egg duck eggs in brine, or packing each egg
date:     "2015-05-01T22:12:03.284Z"
path:     "/hello-world/"
image:    "./salty_egg.jpg"
tags:
  - remark
  - Images
  - Videos
  - iFrames
author:    alexng
---

This is my first post on my new fake blog! How exciting!

gatsby-config.js

module.exports = {
  pathPrefix: `/gopher.it-Gatsby`,
  siteMetadata: {
    title: "Gopher Labs Ltd.",
    author: "Eliad Moosavi",
    siteUrl: "https://gopher.it"
  },
  plugins: [
    `gatsby-plugin-sass`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/pages`,
        name: "pages",
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 590,
            },
          },
          {
            resolve: `gatsby-remark-responsive-iframe`,
            options: {
              wrapperStyle: `margin-bottom: 1.0725rem`,
            },
          },
          {
            resolve: `gatsby-remark-prismjs`,
            options: {
              classPrefix: 'language-',
            },
          },
          "gatsby-remark-copy-linked-files",
          "gatsby-remark-smartypants",
          {
            resolve: `gatsby-plugin-nprogress`,
            options: {
              // Setting a color is optional. 
              color: `tomato`,
            }
          }
        ],
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-feed`
    },
    `gatsby-plugin-offline`,
    `gatsby-plugin-react-helmet`,
    {
      resolve: "gatsby-plugin-typography",
      options: {
        pathToConfigModule: "src/utils/typography",
      },
    },
  ],
}

package.json

{
  "name": "gatsby-starter-blog",
  "description": "Starter Gatsby Blog",
  "version": "1.0.0",
  "author": "Kyle Mathews <mathews.kyle@gmail.com>",
  "bugs": {
    "url": "https://github.com/gatsbyjs/gatsby-starter-blog/issues"
  },
  "dependencies": {
    "bulma": "^0.5.1",
    "gatsby": "^1.8.12",
    "gatsby-link": "^1.6.8",
    "gatsby-plugin-feed": "^1.3.5",
    "gatsby-plugin-google-analytics": "^1.0.4",
    "gatsby-plugin-manifest": "^1.0.4",
    "gatsby-plugin-nprogress": "^1.0.3",
    "gatsby-plugin-offline": "^1.0.4",
    "gatsby-plugin-preact": "^1.0.3",
    "gatsby-plugin-react-helmet": "^1.0.3",
    "gatsby-plugin-sharp": "^1.6.2",
    "gatsby-plugin-typography": "^1.7.6",
    "gatsby-remark-copy-linked-files": "^1.5.2",
    "gatsby-remark-images": "^1.5.4",
    "gatsby-remark-prismjs": "^1.2.1",
    "gatsby-remark-responsive-iframe": "^1.4.3",
    "gatsby-remark-smartypants": "^1.4.3",
    "gatsby-source-filesystem": "^1.4.3",
    "gatsby-transformer-remark": "^1.7.1",
    "gatsby-transformer-sharp": "^1.6.1",
    "lodash": "^4.15.0",
    "react-disqus-thread": "^0.4.0",
    "react-responsive-grid": "^0.3.3",
    "typeface-merriweather": "^0.0.35",
    "typeface-montserrat": "^0.0.37",
    "typography-theme-wordpress-2016": "^0.15.1"
  },
  "devDependencies": {
    "gatsby-plugin-sass": "^1.0.3",
    "gh-pages": "^0.12.0",
    "prettier": "^1.5.3"
  },
  "homepage": "https://github.com/gatsbyjs/gatsby-starter-blog#readme",
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "main": "n/a",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/gatsbyjs/gatsby-starter-blog.git"
  },
  "scripts": {
    "dev": "gatsby develop",
    "lint": "./node_modules/.bin/eslint --ext .js,.jsx --ignore-pattern public .",
    "test": "echo \"Error: no test specified\" && exit 1",
    "format": "prettier --trailing-comma es5 --no-semi --single-quote --write 'src/**/*.js'",
    "develop": "gatsby develop",
    "build": "gatsby build",
    "deploy": "gatsby build --prefix-paths && gh-pages -d public",
    "fix-semi": "eslint --quiet --ignore-pattern node_modules --ignore-pattern public --parser babel-eslint --no-eslintrc --rule '{\"semi\": [2, \"never\"], \"no-extra-semi\": [2]}' --fix gatsby-node.js"
  }
}

gatsby-node.js

const _ = require("lodash")
const Promise = require("bluebird")
const path = require("path")
const select = require(`unist-util-select`)
const fs = require(`fs-extra`)

exports.createPages = ({ graphql, boundActionCreators }) => {
  const { createPage } = boundActionCreators

  return new Promise((resolve, reject) => {
    const pages = []
    const blogPost = path.resolve("./src/templates/blog-post.js")
    resolve(
      graphql(
        `
      {
        allMarkdownRemark(limit: 1000) {
          edges {
            node {
              frontmatter {
                path
              }
            }
          }
        }
      }
    `
      ).then(result => {
        if (result.errors) {
          console.log(result.errors)
          reject(result.errors)
        }

        // Create blog posts pages.
        _.each(result.data.allMarkdownRemark.edges, edge => {
          console.log(edge.node.frontmatter.path);

          createPage({
            path: "/blog" + edge.node.frontmatter.path,
            component: blogPost,
            context: {
              path: edge.node.frontmatter.path,
            },
          })
        })
      })
    )
  })
}
@theiliad theiliad changed the title Adding a photo field (with a relative path) to .md files Adding an image field (with a relative path) to .md files Aug 22, 2017
@whmountains
Copy link

Judging by the error message it looks like you need to specify what attributes of the image you want. Something like this:

image {
  src
}

Graphiq can help you know what options you have for subfields.

@theiliad
Copy link
Contributor Author

@whmountains Even when I add src in, it says "GraphQL Error: Uknown field 'src' on type 'image'

How would I get into GraphQL?

@theiliad
Copy link
Contributor Author

Got into GraphQL, do you have any ideas on how I would start querying?

@planigan
Copy link

planigan commented Aug 27, 2017

@theiliad From tutorial part 4 section Introducing GraphiQL, you can hit Ctrl+Space to open the autocomplete and Ctrl+Enter to run the query.

@sgriffey
Copy link

@theiliad did you ever make a tutorial for this?

@mpolinowski
Copy link

Just ran into the same issue - the solution for me is:

Subfields missing:

export const pageQuery = graphql`
  query ArticlesByPath($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        path
        title
        excerpt
        author
        image
      }
    }
  }
`;

Working example with subfields added:

export const pageQuery = graphql`
  query ArticlesByPath($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        path
        title
        excerpt
        author
        image {
          childImageSharp {
              resize(width: 597, height: 382){
                src
                }
          }
        },
      }
    }
  }
`;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants