Coder Social home page Coder Social logo

danielmahon / gatsby-remark-relative-images Goto Github PK

View Code? Open in Web Editor NEW
79.0 4.0 29.0 4.38 MB

Convert markdown image src(s) to be relative for gatsby-remark-images.

Home Page: https://www.npmjs.com/package/gatsby-remark-relative-images

License: BSD Zero Clause License

TypeScript 98.66% JavaScript 1.34%
gatsby-plugin remark-plugin relative gatsby-remark-images gatsby netlify-cms

gatsby-remark-relative-images's Introduction

🛠 Hello, I need a maintainer 👩‍💻 🧑‍💻 🛠

As you can probably see, I have not maintained, or used this package (or Gatsby for that matter) in a number of years. Frankly, I'm surprised this package still needs to exist. I have no plans to continue working on this so if you would like to take over this repo please let me know.

gatsby-remark-relative-images

Convert image src(s) in markdown/html/frontmatter to be relative to their node's parent directory. This will help gatsby-remark-images match images outside the node folder. This was built for use with NetlifyCMS and should be considered a temporary solution until relative paths are supported. If it works for other use cases then great!

Features

  • Converts markdown/mdx images
  • Converts src in markdown/mdx html <img /> tags
  • Converts frontmatter fields, supports nested fields
  • Suports Unicode characters
  • Frontmatter field filters (include/exclude)

v2 Breaking Changes:

The fmImagesToRelative() function has been removed, it is no longer needed.

NOTE: v2 greatly simplifies things and seems to work well for my use-case (NetlifyCMS), if you were previously using this plugin for something else that no longer works with v2, please open an issue and let me know and I will try to accomodate your use-case. Thanks.

Install

# Install v2 (Recommended)
yarn add gatsby-remark-relative-images

# Install v1 (TS refactor, but quickly found more things to simplfy, skip)
npm i [email protected]

# Install original (a bit hacky but have previously worked for most)
npm i [email protected]
npm i [email protected]

Usage Example

This usage example is for v2 of this plugin.

/gatsby-config.js

module.exports = {
  plugins: [
    // Add static assets before markdown files
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/static/uploads`,
        name: 'uploads',
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          // gatsby-remark-relative-images must go before gatsby-remark-images
          {
            resolve: `gatsby-remark-relative-images`,
            options: {
              // [Optional] The root of "media_folder" in your config.yml
              // Defaults to "static"
              staticFolderName: 'static',
              // [Optional] Include the following fields, use dot notation for nested fields
              // All fields are included by default
              include: ['featured'],
              // [Optional] Exclude the following fields, use dot notation for nested fields
              // No fields are excluded by default
              exclude: ['featured.skip'],
            },
          },
          {
            resolve: `gatsby-remark-images`,
            options: { maxWidth: 1024 },
          },
        ],
      },
    },
  ],
};

/static/admin/config.yml

# ...
media_folder: static/img
public_folder: /img
# ...

/src/pages/blog-post.md

---
templateKey: blog-post
title: A beginners’ guide to brewing with Chemex
date: 2017-01-04T15:04:10.000Z
featured: { image: /img/chémex.jpg, skip: /img/chémex.jpg }
<!-- featured: { image: ../../static/img/chémex.jpg, skip: /img/chémex.jpg } -->
description: Brewing with a Chemex probably seems like a complicated, time-consuming ordeal, but once you get used to the process, it becomes a soothing ritual that's worth the effort every time.
---

![chemex](/img/chémex.jpg)

<!-- ![chemex](../../static/img/chémex.jpg) -->

This week we’ll **take** a look at all the steps required to make astonishing coffee with a Chemex at home. The Chemex Coffeemaker is a manual, pour-over style glass-container coffeemaker that Peter Schlumbohm invented in 1941, and which continues to be manufactured by the Chemex Corporation in Chicopee, Massachusetts.

In 1958, designers at the [Illinois Institute of Technology](https://www.spacefarm.digital) said that the Chemex Coffeemaker is _"one of the best-designed products of modern times"_, and so is included in the collection of the Museum of Modern Art in New York City.

## The little secrets of Chemex brewing

<img src="/img/chémex.jpg" alt="" style="width: 250px" />
<!-- <img src="../../static/img/chémex.jpg" alt="" style="width: 250px" /> -->

The Chemex Coffeemaker consists of an hourglass-shaped glass flask with a conical funnel-like neck (rather than the cylindrical neck of an Erlenmeyer flask) and uses proprietary filters, made of bonded paper (thicker-gauge paper than the standard paper filters for a drip-method coffeemaker) that removes most of the coffee oils, brewing coffee with a taste that is different than coffee brewed in other coffee-making systems; also, the thicker paper of the Chemex coffee filters may assist in removing cafestol, a cholesterol-containing compound found in coffee oils.

FAQs

I'm getting the error: Field "image" must not have a selection since type "String" has no subfields

This is a common error when working with Netlify CMS (see issue gatsby/gatsby#5990).

The application must include the media with gatsby-source-filesystem to include all the uploaded media and to make it available on build time. Note: The media folder must be included before the other content.

For example, an application that is using NetlifyCMS and this plugin, and has a content folder with markdown that comes from Netlify. Here's how the gatsby-config.js should look like:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/static/assets`,
        name: 'assets',
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/content`,
        name: 'content',
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          `gatsby-remark-relative-images`,
          {
            resolve: `gatsby-remark-images`,
            options: {},
          },
        ],
      },
    },
    `gatsby-plugin-netlify-cms`,
  ],
};

gatsby-remark-relative-images's People

Contributors

alexandernanberg avatar axelboc avatar chawes13 avatar codyray avatar daguima-dag avatar danielmahon avatar geekmasher avatar giraffesyo avatar hanakla avatar hennessyevan avatar jmendiara avatar kinduff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

gatsby-remark-relative-images's Issues

After migrate to 0.3.0, images doesn't work

Hi,

In last week I've updated the dependency for 0.2.3 to 0.3.0 and images didn't work more.

I can't understand what is the cause of problem, but I think that gatsby-remark-relative-images doesn't resolve the paths anymore.

For example (in prod), in 0.3.0:

<img src="assets/2019-11-27-github-explore.png" alt="Github Explore">

In 0.2.3 working well.

a 2.0.3 release for gatsby-remark-relative-images with updated lodash

Hi, @danielmahon,

Issue Description

I noticed that a vulnerability is introduced in [email protected]:
Vulnerability CVE-2021-23337 (high severity) affects package lodash (versions:<4.17.21): https://snyk.io/vuln/SNYK-JS-LODASHTEMPLATE-1088054
The above vulnerable package is referenced by [email protected] via:
[email protected][email protected]

Since [email protected] (3,474 downloads per week) is referenced by 69 downstream projects (e.g., gatsby-theme-kepler 1.7.728, gatsby-theme-catalyst-core 7.0.4, gatsby-theme-catalyst-hydrogen, gatsby-theme-catalyst-bery 7.0.4), the vulnerability CVE-2021-23337 can be propagated into these downstream projects and expose security threats to them via the following package dependency paths:
(1)[email protected][email protected][email protected][email protected]
......

If [email protected].* removes the vulnerable package from the above version, then its fixed version can help downstream users decrease their pain.

Given the large number of downstream users, could you help update your package to remove the vulnerability from [email protected] ?

Fixing suggestions

In [email protected], maybe you can kindly try to perform the following upgrade :
lodash 4.17.20 ➔ 4.17.21;

Note:
[email protected](>=4.17.21) has fixed the vulnerability CVE-2021-23337.

Thank you for your attention to this issue and welcome to share other ways to resolve the issue.

Best regards,
^_^

support also non-file markdown remark nodes

Currently it is not easily possible to have markdown in frontmatter tags while using this plugin (e.g. using netlifyCMS with a markdown fields other than Body).
Currently I am creating new nodes for these frontmatter fields

exports.onCreateNode = async ({ node, actions, getNode }) => {
  const { createNode, createNodeField } = actions;

  if (node.internal.type === `MarkdownRemark`) {
    if (node.frontmatter && node.frontmatter.myMarkDownField) {
      const infoNode = await createNode({
        id: `md-${node.id}-info`,
        parent: node.id,
        children: [],
        internal: {
          type: `InfoMarkdown`,
          mediaType: `text/markdown`,
          content: node.frontmatter.myMarkDownField,
          contentDigest: node.internal.contentDigest,
        },
      });

(similar to the suggestion here hygraph/gatsby-source-graphcms#44 (comment))

However transformer remark only copies the absolutePath in case its a File node (which it clearly isnt).
So I would need some way to indicate the absolute path in the remark node or maybe have some other field conveying the path.
Currently the code only works if the markdown node has a fileAbsolutePath (see https://github.com/danielmahon/gatsby-remark-relative-images/blob/master/src/on-create-node.ts#L29), which is not the case for me and therefore the plugin crashes currently.


"gatsby-remark-relative-images" threw an error while running the onCreateNode lifecycle:

The "path" argument must be of type string. Received type undefined



  Error: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined

  - validators.js:112 validateString
    internal/validators.js:112:11

  - on-create-node.js:15 Object.exports.onCreateNode
    [gatsby-starter-netlify-cms]/[gatsby-remark-relative-images]/dist/on-create-node.js:15:42

  - api-runner-node.js:330 runAPI
    [gatsby-starter-netlify-cms]/[gatsby]/src/utils/api-runner-node.js:330:22

  - api-runner-node.js:440 Promise.catch.decorateEvent.pluginName
    [gatsby-starter-netlify-cms]/[gatsby]/src/utils/api-runner-node.js:440:17

  - From previous event:

  - api-runner-node.js:440 Promise.catch.decorateEvent.pluginName
    [gatsby-starter-netlify-cms]/[gatsby]/src/utils/api-runner-node.js:440:9

  - From previous event:

  - api-runner-node.js:439
    [gatsby-starter-netlify-cms]/[gatsby]/src/utils/api-runner-node.js:439:14

Subfolders in assets result in overwrite images having the same names

If there are subfolders inside assets which contain images have same names, like:

- assets
|_ sub-folder-1
|___ image1.png
|_ sub-folder-2
|___ image1.png

the following markdown will display /assets/sub-folder-2/image1.png for both of images:

[my-first-image](./assets/sub-folder-1/image1.png)
[my-second-image](./assets/sub-folder-2/image1.png)

Not able to change to relative path in markdown

I really appreciate your work on this plugin. For some reason I can't get it to work on my Gatsby app. In index.md, I have this frontmatter:

      ---
      templateKey: home-page/index
      image1: /img/City-Picture.jpg
      ---

In home-page/index.js, I have this query:

export const homePageQuery = graphql`
  query HomePage($id: String!) {
    markdownRemark(id: { eq: $id }) {
      frontmatter {
        welcome_description
        image1 {
          childImageSharp {
            sizes(maxWidth: 590) {
              ...GatsbyImageSharpSizes
            }
          }
        }
      }
    }
 }

In gatsby-config.js, I have:

module.exports = {
  siteMetadata: {
    title: 'Gatsby + Netlify CMS Starter',
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/pages`, // path to markdown files
        name: `pages`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/static/img`,
        name: `images`,
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          // gatsby-remark-relative-images must
          // go before gatsby-remark-images
          {
            resolve: `gatsby-remark-relative-images`,
          },
          {
            resolve: `gatsby-remark-images`,
            options: {
              // It's important to specify the maxWidth (in pixels) of
              // the content container as this plugin uses this as the
              // base for generating different widths of each image.
              maxWidth: 590,
            },
          },
        ],
      },
    },
    {
      resolve: `gatsby-plugin-netlify-cms`,
      options: {
        modulePath: `${__dirname}/src/cms/cms.js`,
      },
    },
    `gatsby-plugin-meta-redirect`, 
    `gatsby-plugin-netlify`, // make sure to keep it last in the array
  ],
}

In config.yml I have:

    media_folder: static/img
    public_folder: /img

In 325 you had mentioned that:

"So, given a node like /src/pages/blog/my-first-post.md, with an image src of /uploads/fat-racoon.jpg, and the referenced image in /static/uploads it changes the node.url to .../.../../static/uploads/fat-racoon.jpg. Which lets gatsby-remark-images resolve it correctly when it does path.join(node.parent.dir, node.url)."

For some reason when I run it in development or build mode, image1 remains as /img/City-Talk-Class.jpg and does not transform into ../../static/img/City-Talk-Class.jpg as I'd prefer.

I keep getting this error in my terminal:

GraphQL Error Field "image1" must not have a selection since type "String" has no subfields.
     2 |   query HomePage($id: String!) {
     3 |     markdownRemark(id: { eq: $id }) {
     4 |       frontmatter {
     5 |         welcome_description
     6 |         image1 {
        |                ^
     7 |           childImageSharp {
     8 |             sizes(maxWidth: 590) {
     9 |               ...GatsbyImageSharpSizes
    10 |             }
    11 |           }
    12 |         }
    13 |       }
  14 |     }

Can you tell if I am implementing your plugin incorrectly? Thank you so much!

Images not found with version 2

I'm using netlify and have followed your instructions but the images are not found.

Here is my gatsby-config:

module.exports = {
  plugins: [
    'gatsby-plugin-react-helmet',
    'gatsby-transformer-yaml',
    {
      resolve: 'gatsby-plugin-google-tagmanager',
      options: ...
    },
    {
      resolve: 'gatsby-plugin-offline',
      options: ...
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        ...
      }
    },
    // Add static assets before markdown files and images
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/static/assets`,
        name: 'images'
      }
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/content`,
        name: 'pages'
      }
    },
    // images
    'gatsby-plugin-image',
    'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          // gatsby-remark-relative-images must
          // go before gatsby-remark-images
          'gatsby-remark-relative-images',
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 800,
              linkImagesToOriginal: false
            }
          },
          `gatsby-remark-responsive-iframe`
        ]
      }
    },
    {
      resolve: `@leomanlapera/gatsby-source-yelp`,
      options: {
        ...
      }
    },
    {
      resolve: 'gatsby-plugin-nprogress',
      options: {
        ...
      }
    },
    'gatsby-plugin-sitemap',
    {
      resolve: 'gatsby-plugin-netlify-cms',
      options: {
        ...
      }
    },
    'gatsby-plugin-netlify' // make sure to keep it last in the array
  ]
}

Strict mode for invalid image paths

I've encountered that if I wanted to throw an exception detailing:

  • which file contained an invalid path to an image
  • The actual invalid path

I can not get the latter, given that the node created for an invalid path is null when querying it.

Is there any way one can get the string for the invalid path? Is there any way for the plugin to be strict about the validity of every path?

Convert absolute paths in JSON files

Do you have any plans to also process JSON files? That would be really handy!

e.g. I have JSON files in the /data folder that contain absolute paths to images ("/assets/etc.jpg") that, similarly, need to be converted to relative paths.

Why is the images I queried is so tiny

Please help The base64 images I get is so tiny

Below is my Query

query Services {
   allMarkdownRemark(filter: {frontmatter: {categories: {eq: "services"}}}) {
           edges {
               node {
                   frontmatter {
                       categories
                       title
                        thumbnail {
                          childImageSharp {
                            id
                           fluid(maxWidth:3000){
                             base64
                           }
                          }
                        }
                   }
               }
           }
       }
   }

Here's the results

{
  "data": {
    "allMarkdownRemark": {
      "edges": [
        {
          "node": {
            "frontmatter": {
              "categories": "services",
              "title": "Frontend Development",
              "thumbnail": {
                "childImageSharp": {
                  "id": "bcf3d86c-fb81-504e-91df-c31ed9e92fb8",
                  "fluid": {
                    "base64": "data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAIABQDASIAAhEBAxEB/8QAFwABAAMAAAAAAAAAAAAAAAAAAAEDBf/EABQBAQAAAAAAAAAAAAAAAAAAAAH/2gAMAwEAAhADEAAAAdWBLAP/xAAWEAADAAAAAAAAAAAAAAAAAAACEDH/2gAIAQEAAQUCKL//xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAEDAQE/AT//xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAECAQE/AT//xAAUEAEAAAAAAAAAAAAAAAAAAAAQ/9oACAEBAAY/An//xAAZEAEAAgMAAAAAAAAAAAAAAAABESEAEGH/2gAIAQEAAT8h6Rg2Ws6//9oADAMBAAIAAwAAABCH7//EABcRAQADAAAAAAAAAAAAAAAAAAEQESH/2gAIAQMBAT8QHaj/xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAECAQE/ED//xAAZEAEBAQADAAAAAAAAAAAAAAABESEAEDH/2gAIAQEAAT8QuItGnFB1vQgdf//Z"
                  }
                }
              }
            }
          }
        },
        {
          "node": {
            "frontmatter": {
              "categories": "services",
              "title": "Fullstack Developement",
              "thumbnail": {
                "childImageSharp": {
                  "id": "462b078d-0203-52df-8e69-15c12acba463",
                  "fluid": {
                    "base64": "data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAIABQDASIAAhEBAxEB/8QAFwABAAMAAAAAAAAAAAAAAAAAAAECBf/EABYBAQEBAAAAAAAAAAAAAAAAAAMCBP/aAAwDAQACEAMQAAAB0oMq2B1//8QAFBABAAAAAAAAAAAAAAAAAAAAEP/aAAgBAQABBQJ//8QAFBEBAAAAAAAAAAAAAAAAAAAAEP/aAAgBAwEBPwE//8QAFhEAAwAAAAAAAAAAAAAAAAAAARAx/9oACAECAQE/ARF//8QAFBABAAAAAAAAAAAAAAAAAAAAEP/aAAgBAQAGPwJ//8QAFhAAAwAAAAAAAAAAAAAAAAAAARAh/9oACAEBAAE/ITH/AP/aAAwDAQACAAMAAAAQd/8A/8QAFhEBAQEAAAAAAAAAAAAAAAAAEQEQ/9oACAEDAQE/EKuf/8QAFhEAAwAAAAAAAAAAAAAAAAAAEBFB/9oACAECAQE/EFkf/8QAGRABAAMBAQAAAAAAAAAAAAAAAQARITFB/9oACAEBAAE/EGDVpzIrdXZ4mQ525//Z"
                  }
                }
              }
            }
          }
        },
        {
          "node": {
            "frontmatter": {
              "categories": "services",
              "title": "Logo Design",
              "thumbnail": {
                "childImageSharp": {
                  "id": "0b7666bb-b689-5f3f-aa71-83bc5f87e8f4",
                  "fluid": {
                    "base64": "data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAIABQDASIAAhEBAxEB/8QAFwABAAMAAAAAAAAAAAAAAAAAAAIEBf/EABQBAQAAAAAAAAAAAAAAAAAAAAH/2gAMAwEAAhADEAAAAdCAlED/AP/EABoQAAICAwAAAAAAAAAAAAAAAAECAAMREiH/2gAIAQEAAQUCDDNvV2sE/8QAFREBAQAAAAAAAAAAAAAAAAAAARD/2gAIAQMBAT8BZ//EABURAQEAAAAAAAAAAAAAAAAAAAEQ/9oACAECAQE/ASf/xAAbEAABBAMAAAAAAAAAAAAAAAAAAQIRITEyQf/aAAgBAQAGPwKOlZNGqf/EABoQAAICAwAAAAAAAAAAAAAAAAABETFRcdH/2gAIAQEAAT8hTi6FxEqCrsQf/9oADAMBAAIAAwAAABCHz//EABYRAQEBAAAAAAAAAAAAAAAAABEAAf/aAAgBAwEBPxDATf/EABcRAQADAAAAAAAAAAAAAAAAAAABETH/2gAIAQIBAT8QlbH/xAAZEAEAAwEBAAAAAAAAAAAAAAABABEhUUH/2gAIAQEAAT8Qc6ktXVFfAlXHICvX9i2f/9k="
                  }
                }
              }
            }
          }
        },
        {
          "node": {
            "frontmatter": {
              "categories": "services",
              "title": "Print Design",
              "thumbnail": {
                "childImageSharp": {
                  "id": "afbc817d-7110-5da9-b888-da15289036bd",
                  "fluid": {
                    "base64": "data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAIABQDASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAAAAUC/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAH/2gAMAwEAAhADEAAAAaOhJ4P/xAAZEAACAwEAAAAAAAAAAAAAAAABAgARITL/2gAIAQEAAQUC2IbU9f/EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQMBAT8BP//EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQIBAT8BP//EABoQAAICAwAAAAAAAAAAAAAAAAABIVERcYH/2gAIAQEABj8CjPGVNj2f/8QAGxAAAgEFAAAAAAAAAAAAAAAAAAERITFRYaH/2gAIAQEAAT8hdkGzQGNidg6R/9oADAMBAAIAAwAAABD33//EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQMBAT8QP//EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQIBAT8QP//EABsQAQEAAgMBAAAAAAAAAAAAAAERAFEhQWGB/9oACAEBAAE/EEky1RwTbjq0FC19ubl7Puf/2Q=="
                  }
                }
              }
            }
          }
        },
        {
          "node": {
            "frontmatter": {
              "categories": "services",
              "title": "Web Design",
              "thumbnail": {
                "childImageSharp": {
                  "id": "fc80f4ce-5286-5fb0-9a25-554d35a3edef",
                  "fluid": {
                    "base64": "data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAIABQDASIAAhEBAxEB/8QAFwABAAMAAAAAAAAAAAAAAAAAAAEDBP/EABUBAQEAAAAAAAAAAAAAAAAAAAAB/9oADAMBAAIQAxAAAAHZJFoP/8QAGRABAQADAQAAAAAAAAAAAAAAAgEDERIT/9oACAEBAAEFAvba7Rhymz//xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAEDAQE/AT//xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAECAQE/AT//xAAZEAADAQEBAAAAAAAAAAAAAAAAAREhMVH/2gAIAQEABj8Ci56a6zXGf//EABgQAQADAQAAAAAAAAAAAAAAAAEAEVEh/9oACAEBAAE/IUU3OoXcISlhc//aAAwDAQACAAMAAAAQ/wD/AP/EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQMBAT8QP//EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQIBAT8QP//EABsQAQEAAwADAAAAAAAAAAAAAAERACExQVFh/9oACAEBAAE/EIlbLErNT5zGYpiCh42d94mfd3TP/9k="
                  }
                }
              }
            }
          }
        }
      ]
    }
  }
}

this is my gatsby-config.js

{
   resolve: 'gatsby-source-filesystem',
   options: {
     path: `${__dirname}/static/img`,
     name: 'media',
   },
 },
{

resolve: `gatsby-transformer-remark`,
   options: {
     // CommonMark mode (default: true)
     commonmark: true,
     // Footnotes mode (default: true)
     footnotes: true,
     // Pedantic mode (default: true)
     pedantic: true,
     // GitHub Flavored Markdown mode (default: true)
     gfm: true,
     // Plugins configs
     plugins: [
       // gatsby-remark-relative-images must
       // go before gatsby-remark-images
       {
         resolve: `gatsby-remark-relative-images`,
         options: {
           name: "media" // Must match the source name ^
         }
       },
       {
         resolve: `gatsby-remark-images`,
         options: {
           // It's important to specify the maxWidth (in pixels) of
           // the content container as this plugin uses this as the
           // base for generating different widths of each image.
           maxWidth: 590,
         },
       },
     ],
   },
 },

Cannot find module file index

Installed to deal with Netlify CMS, but it seems to have upset the entire site. First error is

**Error:** Cannot find module 'project/node_modules/gatsby-remark-relative-images/index'

This seems to cause an flow on effect with errors like:

"gatsby-transformer-remark" threw an error while running the createSchemaCustomization lifecycle:
Cannot read properties of undefined (reading 'createSchemaCustomization')

And then it cannot find any of the image files

I'm on version 2.0.2
gatsby-config.js

plugins: [
    {
        resolve: `gatsby-source-filesystem`,
        options: {
            name: `blog`,
            path: `${__dirname}/content/blog`,
        },
        __key: "blog",
    },
    {
        resolve: `gatsby-source-filesystem`,
        options: {
            name: `portfolio`,
            path: `${__dirname}/content/portfolio`,
        },
        __key: "portfolio",
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: "./src/images/",
      },
      __key: "images",
    },

    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    {
        resolve: 'gatsby-transformer-remark',
        options: {
          plugins: [
            'gatsby-remark-relative-images',
            {
              resolve: `gatsby-remark-images`,
              options: {
                maxWidth: 630,
              },
            },
            {
              resolve: `gatsby-remark-responsive-iframe`,
              options: {
                wrapperStyle: `margin-bottom: 1.0725rem`,
              },
            },
            `gatsby-remark-prismjs`,
            `gatsby-remark-copy-linked-files`,
            `gatsby-remark-smartypants`,
          ],
        },
      },

    "gatsby-plugin-netlify-cms",
    "gatsby-plugin-sass",
]

The "path" argument must be a type of string. (breaks on upgrade from 0.2.3 to 0.3.0

I had to trial an error update all my packages to find it was this plugin causing the error. It wasn't very descriptive.

0.2.3 works fine, but 0.3.0 breaks.

This is the error:

CleanShot 2020-07-31 at 11 52 58@2x

CleanShot 2020-07-31 at 11 53 21@2x

This is my config:

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/`
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/assets/images/`
      }
    },

......

{
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-source-contentful`,
            options: {
              spaceId: process.env.CONTENTFUL_SPACE_ID,
              accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
              host: process.env.CONTENTFUL_HOST
            }
          },
          `gatsby-remark-relative-images`,
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 750,
              linkImagesToOriginal: false
            }
          }
        ]
      }
    },

Any ideas as to what's going on? Apparently it's saying my paths aren't strings anymore, but nothing has changed.

Failed transform relative image

Hi, I try to follow the documentation but still no luck. The image field still detected as a sting Field "src" must not have a selection since type "String" has no subfields

Here is my directory

  ↳ content
    ↳ pages
      ↳ homepage.md
    ↳ images
      ↳ foo.jpeg
      ↳ bar.jpeg
  ↳ src
  ↳ static
    ↳ images
      ↳ foo.jpeg
      ↳ bar.jpeg
// gatsby config
plugins: [

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/static/images`, // or ${__dirname}/content/images  
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `pages`,
        path: `${__dirname}/content/pages`, // Content pages
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          // if using gatsby-remark-relative-images then place it before gatsby-remark-images
          {
            resolve: `gatsby-remark-relative-images`,
            options: {
              // [Optional] The root of "media_folder" in your config.yml
              // Defaults to "static"
              staticFolderName: 'static',
              // [Optional] Include the following fields, use dot notation for nested fields
              // All fields are included by default
              include: ['hero.image.src'],
              // [Optional] Exclude the following fields, use dot notation for nested fields
              // No fields are excluded by default
              exclude: ['hero.image.alt'],
            },
          },
          {
            resolve: 'gatsby-remark-images',
            options: {
              quality: 100,
              maxWidth: 720,
              linkImagesToOriginal: false,
              backgroundColor: `#edf2f7`,
              disableBgImage: true,
              withWebp: true,
              showCaptions: [`title`, `alt`],
            }
          },
        ]
      }
    },
  ],
---
hero:
   ....
    image:
        src: /images/foo.png
        alt: foo
---

this is my query result

{
  "data": {
    "allMarkdownRemark": {
      "edges": [
        {
          "node": {
            "id": "ecc01a86-2259-57a4-aff5-26b3cd424fc1",
            "frontmatter": {
              "hero": {
                "intro": "Gunarupa Studio",
                "image": {
                  "src": "/images/astronaut.png"
                }
              }
            }
          }
        }
      ]
    }
  },
  "extensions": {}
}
  System:
    OS: Windows 10 10.0.18362
  npmPackages:
    gatsby: ^2.24.57 => 2.24.57
    gatsby-image: ^2.4.16 => 2.4.16
    gatsby-plugin-draft: 0.0.5 => 0.0.5
    gatsby-plugin-manifest: ^2.4.24 => 2.4.24
    gatsby-plugin-netlify-cms: ^4.3.14 => 4.3.14
    gatsby-plugin-offline: ^3.2.24 => 3.2.24
    gatsby-plugin-postcss: ^2.3.11 => 2.3.11
    gatsby-plugin-preact: ^4.0.10 => 4.0.10
    gatsby-plugin-react-helmet: ^3.3.10 => 3.3.10
    gatsby-plugin-react-svg: ^3.0.0 => 3.0.0
    gatsby-plugin-sharp: ^2.6.35 => 2.6.35
    gatsby-plugin-typescript: ^2.4.19 => 2.4.19
    gatsby-remark-images: ^3.3.29 => 3.3.29
    gatsby-remark-normalize-paths: ^1.0.0 => 1.0.0
    gatsby-remark-relative-images: ^2.0.2 => 2.0.2
    gatsby-source-filesystem: ^2.3.25 => 2.3.25
    gatsby-transformer-remark: ^2.8.32 => 2.8.32
    gatsby-transformer-sharp: ^2.5.13 => 2.5.13
    gatsby-transformer-yaml: ^2.4.11 => 2.4.11
  npmGlobalPackages:
    gatsby-cli: 2.12.97

I try to use content and static directory but none of them working

FYI

  • in my previous project i'm using 0.2.3 which have fmImagesToRelative function
  • at the moment I haven't used a CMS but the plan is Forestry which i think is similiar to Netlify CMS

For temporary solution i revert the plugin to the version 0.2.3, is ti any step that i missed or the latest version have no support for this kind approach?

Field "bannerImage" must not have a selection since type "String" has no subfields.

I would love to upgrade, however when upgrading to 2.0.2 (from 0.2.3), I am getting the titled error with no changes other than having removed fmImagesToRelative as recommended in my gatsby-node.js. I am using NetlifyCMS in conjunction with Gatsby, like you, so I'm curious where the breakdown is occurring.

My config.yml values align exactly with yours. Here's the relevant excerpt from my gatsby-config.js file (some plugins omitted for brevity):

{
//...
  "plugins" : {
//...
        resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/static/img`,
        name: "uploads",
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/src/pages`,
        name: "pages",
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/src/img`,
        name: "images",
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/src/content`,
        name: "content",
      },
    },
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          "gatsby-remark-relative-images",
          {
            resolve: "gatsby-remark-images",
            options: {
              maxWidth: 800,
              linkImagesToOriginal: false,
              quality: 90,
              showCaption: true,
            },
          },
// etc ...
  }
}

Pretty standard stuff. The only difference I can see is in my markdown frontmatter:

---
bannerImage: /img/sheila-anne-writing-desk.jpg
# etc ...
---

Whereas it seems (in your readme example at least) that you have the paths contained within an object. When querying the updated fields (the GraphQL server starts up even though the bundle for the site fails to be created, thankfully), I can see that they are still strings, but with some updates: ..\..\..\static\img\sheila-anne-writing-desk.jpg

This is an open source repo, hopefully that helps.

In short - thanks for your hard work on this plugin. Hopefully we can get to the bottom of the issue!

Document required Netlify CMS configuration

If I'm not mistaken, the plugin assumes that the configured Netlify CMS public_folder is one level down from the media_folder - e.g.

media_folder: "static/uploads"
public_folder: "/uploads"

I'm referring more specifically to line 129:

imagePath = path.join(file.dir, '..', value);

If that's the case, it might be worth mentioning it in the README.

ReferenceError: regeneratorRuntime is not defined

Got the above error when upgrading gatsby to v2.0.0-beta.2

- index.js:48 
    [gatsby-remark-relative-images]/index.js:48:7
  
  - index.js:94 
    [gatsby-remark-relative-images]/index.js:94:6
  
  - Array.map
  
  - index.js:42 module.exports
    [gatsby-remark-relative-images]/index.js:42:22

frontmatter gallery images not transformed

I hope this is the right place to share my issue. For arrays of image paths like my frontmatter gallery, the paths are not being transformed.

---
gallery:
- "/content/images/20160821_004637.jpg"
- "/content/images/20160524_221520.jpg"
hero_image: "/content/images/20160821_004637.jpg"
---

In the frontmatter above, the hero_image is transformed as expected but the gallery strings are left unchanged.
My gatsby-config plugins are set up like so:

"gatsby-plugin-styled-components",
    `gatsby-plugin-react-helmet`,
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "events",
        path: `${__dirname}/content/events`,
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: `${__dirname}/content/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          "gatsby-remark-relative-images",
          "gatsby-remark-normalize-paths",
          {
            resolve: "gatsby-remark-images",
            options: {
              maxWidth: 1000,
              linkImagesToOriginal: false,
            },
          },
        ],
      },
    },

Any help would be appreciated, thanks!

Gatsby 4: graph gets null images in some cases

Hi, we're using this with NetlifyCMS in a production project, thanks for the plugin!

I'm not sure whether this is a low-level Gatsby problem or something to do with this plugin but I'm getting a weird new regression where images are returning null in some cases and not others. All images are typed in the schema as File @fileByRelativePath and we've had the site live using Gatsby 3 for a while without any problems.

We're trying to upgrade to latest Gatsby (4.21) and React 18.2 and this is blocking us. Anything you've encountered before? Thanks

Schema does not update without restarting 'gatsby develop'

Screenshot 2020-09-02 at 13 12 33

When editing images in Frontmatter while in development mode, the GraphQL queries break with the Field "gallery_images" must not have a selection since type "[String]" has no subfields. until you restart gatsby develop.

You can repro by commenting out an image in a list like this while running development
Screenshot 2020-09-02 at 13 42 00

Relative paths not recognized by remark

Hi! I've been trying to get V2 to work with Netlify CMS, but I'm stuck:
Image paths are getting transformed to relative paths, such as:

"..\\..\\..\\static\\img\\78255412_1542951075843738_6829112130805956608_o.jpg"

but, looking in GraphiQL, the field in frontmatter is still a string, never being transformed into an ImageSharp object.
I did put the plugin before gatsby-remark-images, so I don't know what might be happening.
I believe it might have something to do with the path module using the double slashes in windows instead of a forward slash. Gatsby/Sharp recognizes that path when using forward slashes.

Thanks for the attention.

Transformation not working with special characters in path (like é)

This path is correctly transformed:
"image": "/uploads/jumbotron.jpg" -> "image": "../../uploads/jumbotron.jpg"
This path is not:
"image": "/uploads/macaron-animé.png" -> "image": "..\\uploads\\macaron-animé.png"
When removing the accent in the filename, everything works.

From what I checked, the problem can be resolved by removing the outdated "slash" dependency and using gatsby-core-utils where the same function was fixed and is working as expected.
gatsbyjs/gatsby@9929cf0#diff-039be84c08b1575fb3dbce971ae4089a
PR here: gatsbyjs/gatsby#14372

Env:

    OS: Windows 10 10.0.18363
    CPU: (16) x64 AMD Ryzen 7 3700X 8-Core Processor
  Binaries:
    Node: 13.0.1 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.21.1 - C:\Users\arnod\AppData\Roaming\npm\yarn.CMD
    npm: 6.13.4 - C:\Program Files\nodejs\npm.CMD
  Languages:
    Python: 3.8.0
  Browsers:
    Edge: 44.18362.449.0
  npmPackages:
    gatsby: 2.17.17 => 2.17.17
    gatsby-image: ^2.2.37 => 2.2.37
    gatsby-plugin-netlify: ^2.1.30 => 2.1.30
    gatsby-plugin-netlify-cms: ^4.1.33 => 4.1.33
    gatsby-plugin-purgecss: ^4.0.0 => 4.0.1
    gatsby-plugin-react-helmet: ^3.0.4 => 3.1.18
    gatsby-plugin-sass: ^2.0.7 => 2.1.26
    gatsby-plugin-sharp: ^2.3.10 => 2.3.10
    gatsby-remark-copy-linked-files: ^2.1.33 => 2.1.33
    gatsby-remark-images: ^3.1.39 => 3.1.39
    gatsby-remark-relative-images: ^0.2.3 => 0.2.3
    gatsby-source-filesystem: ^2.0.26 => 2.1.43
    gatsby-transformer-remark: ^2.6.45 => 2.6.45
    gatsby-transformer-sharp: ^2.1.9 => 2.3.9

Plugin stopped working when upgraded to gatsby 2.18.1

After upgrading gatsby to 2.18.1, I go the following error:

Field "featuredImage" must not have a selection since type "String" has no subfields

featuredImage is a field used in frontmatter with an absolute path. So I guess there must be something wrong with fmImagesToRelative.

When switch back to 2.17, the error will disappear.

Can we have a couple of end to end examples please?

Hi,
I realise that this is not necessarily within the scope of the plugin, but it would be really helpful to have the kind of setup we'd need across the board when using this plugin because there are potentially many systems working across each other here - gatsby-source-filesystem, gatsby-transformer-remark, gatsby-remark-images, your plugin AND whatever CMS/editing solution one is using.

I have found that there seem to be conflicting requirements (that may just reveal my incomplete understanding).

For example, I am using NetlifyCMS and I have a folder structure a bit like this:

src -
    pages -
        about -
            index.md
static -
    admin -
        config.yml
    uploads -
        asset.jpg
        

and my gatsby-config.json uses this:

plugins: [
       {
            resolve: `gatsby-source-filesystem`,
            options: {
                path: `${__dirname}/static/uploads`,
                name: "uploads",
            },
        },
        {
            resolve: `gatsby-transformer-remark`,
            options: {
                plugins: [
                    // gatsby-remark-relative-images must
                    // go before gatsby-remark-images
                    {
                        resolve: `gatsby-remark-relative-images`,
                        options: {
                            // Set the name option to the same
                            // name you set for gatsby-source-filesystem
                            name: "uploads", // default
                        },
                    },
                    // Make responsive, blur-up images from markdown images
                    {
                        resolve: `gatsby-remark-images`,
                        options: {
                            maxWidth: 693,
                            wrapperStyle: ` flex: 1; margin: var(--pad-0) 0;`,
                            linkImagesToOriginal: false,
                        },
                    },
                    {
                        resolve: `gatsby-remark-responsive-iframe`,
                        options: {
                            wrapperStyle: `margin-bottom: 1.0725rem`,
                        },
                    },
                    "gatsby-remark-copy-linked-files",
                ],
            },
        },
]

and my static/admin/config.yml has this in it: media_folder: static/uploads. When I look at the built file structure, the content of the uploads folder is moved into public/uploads while imageSharp processed images are placed in public/static.

The issue that I have is my md file (in src/pages/about/index.md) needs the path to be ../../../static/uploads/asset.jpg in order to be a reference from the filesystem plugin and thereby be able to use graphQL to create an imageSharp node. This presents me with an issue because netlify-cms translates the media_folder to an absolute path (in my case that will become /static/uploads) or I can insert a public_folder parameter, which in my case I'd need to point at /img because that is where the build process has copied my files... and therein lies the issue because netlify-cms will use the public_folder as the path to insert into the markdown file, which then breaks the graphQL query because the path doesn't point at a path process by the filesystem plugin.

version 0.3 breaks image captions

Hi,

After upgrading from 0.2 to 0.3, the showCaptions option of gatsby-remark-images stops working. e.g.:

{
  resolve: `gatsby-remark-images`,
  options: {
    showCaptions: ['title'],
  },
}

The version of gatsby-remark-images doesn't seem to make a difference, neither does changing its configuration options. Downgrading back to gatsby-remark-relative-images 0.2 fixes the issue.

Use ^ versions for npm dependencies

Could you please change the dependency versions to be less strict to be future-proof, for instance:

"lodash": "^4.17.11",

The current lodash version produces an npm audit issue:

                              Manual Review                                  
         Some vulnerabilities require your attention to resolve             
                                                                            
      Visit https://go.npm.me/audit-guide for additional guidance           

High Prototype Pollution

Package lodash

Patched in >=4.17.12

Dependency of gatsby-remark-relative-images

Path gatsby-remark-relative-images > lodash

More info https://npmjs.com/advisories/1065

Denial of Service and command injection security issue with npm audit

I receive 2 High security vulnerabilities with gatsby-remark-relative-images

┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High          │ Denial of Service                                            │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ css-what                                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=5.0.1                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ gatsby-remark-relative-images                                │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ gatsby-remark-relative-images > cheerio > css-select >       │
│               │ css-what                                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://npmjs.com/advisories/1754                            │
└───────────────┴────────────────────────────────────────
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High          │ Command Injection                                            │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ lodash                                                       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=4.17.21                                                    │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ gatsby-remark-relative-images                                │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ gatsby-remark-relative-images > lodash                       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://npmjs.com/advisories/1673                            │
└───────────────┴──────────────────────────────────────────────────────────────┘

Plugin seems to be broken on windows

After tracking down an issue here it seems that when using this plugin, the images are not query-able in a windows environment.

The bug is easily reproducible by cloning this repo and attempting the query in the issue. I created a fork that only swaps out this plugin for another solution and the query works as expected on Windows. It has worked as expected on clones on mac and linux OSes. Here's my fork

Relative URL conversion on unwanted frontmatter properies

OK, let me draw up the problem. When I call fmImagesToRelative(node) in the onCreateNode hook of gatsy-node.js, the node argument of the function contains all the node data. Let's say I create a page dynamically according to the markdow below:

`---

title: Title

image: /content/images/image_name.jpg

slug: /my/multilingual/slug`

When this markdown data passed to fmImagesToRelative function, in the inside at row 233. the image validation is like:

if (!file.dir) return;

It means everything that looks like image path is surely an image path. This approach is wrong, because in this way every path will be converted to relative path instead of only paths related to the plugin's settings, eg:

plugins: [... { resolve: 'gatsby-remark-relative-images', options: { name: 'only-this-named-source', }, }, ...]

You should handle this somehow, otherwise we've to face lot of unwanted issues at build process.

The plugin doesn't work in 2.0.2

Summary

Version 0.2.2 used to work ok ✅
Version 2.0.2 doesn't work at all ❌

Detail

In version 0.2.2 we noticed a couple of bugs:

Bug 1

Given the following data structure

blog
├── article-1
│   ├── index.md
│   └── header.jpg
└── article-2
    ├── index.md
    └── header.jpg

Loading article-1 may load header.jpg from article-2

The way around this?

Give unique names to images

For example

blog
├── article-1
│   ├── index.md
│   └── article-1-header.jpg
└── article-2
    ├── index.md
    └── article-2-header.jpg

Bug 2

Given the following image

images/in/some/folder/or/smth/3-secrets-to-relative-image-paths-plz-work.jpg

...has been moved to another location

images/in/some/new-folder/or/smth/3-secrets-to-relative-image-paths-plz-work.jpg

Would build in integration okay

...but then it would break in production with:

Failed to retrieve metadata from image /usr/src/app/www/images/in/some/folder/or/smth/3-secrets-to-relative-image-paths-plz-work.jpg

Notice that the path references the old image in folder and not the new image in new-folder (compare paths above)

So...

I thought I would bump the library to version 2.0.2 to fix the above issues, but now it won't work at all.

I created a small Gatsby Blog Starter repo that has steps to reproduce the issue:

https://github.com/josephmarkus/broken-gatsby-remark-relative-images

Screenshot 2021-06-18 at 09 30 35

Mixed types of paths in frontmatter and body of markdown

Apologies, I am very new to this. This may be related to some prior issues (#15), (#5), and (#18), but I'm not sure...

I recently did a big migration from Medium, and then retroactively populated an image path in my frontmatter. It feels like what I'm doing is pretty hacky, so any thoughts would be appreciated.

In my markdown, my images look like this:
![](/images/0*XRVALKugCEUqoy4O.jpg)

In my frontmatter, my image path look like this:

path:	"/blog/dr-obvious-startup-validation-and-failure"
date:	"2015-12-09"
title:	"Dr. Obvious, Startup Validation, and Failure"
image:	"0*XRVALKugCEUqoy4O.jpg"
---

To complicate things, the paths used in the markdown body (not frontmatter) are "right", whereas the FM image path is relative to the image folder (they are in src/images).

The hack I have to use now is to pass the path to my blogPostTemplate:
image

....and then find it using the relative path:
image

Here is my

  siteMetadata: {
    title: `@johncutlefish's blog`,
    description: `Writing on all things product by John Cutler (@johncutlefish).`,
	  author: `John Cutler`,
		twitterHandle: '@johncutlefish',
		siteURL: 'https://cutle.fish' //this is a bit of a hack
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
	{
	  resolve: `gatsby-source-filesystem`,
	  options: {
	    name: `markdown-pages`,
	    path: `${__dirname}/src/markdown-pages`,
	  },
	},
	`gatsby-transformer-remark`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
	{
	  resolve: `gatsby-transformer-remark`,
	  options: {
	    plugins: [
		  {
		    resolve: `gatsby-remark-relative-images`,
	      },
	      {
	        resolve: `gatsby-remark-images`,
	        options: {
	            // It's important to specify the maxWidth (in pixels) of
	            // the content container as this plugin uses this as the
	            // base for generating different widths of each image.
	            maxWidth: 1200,
	        },
	      },
	    ],
	  },
	},```

Error if using cache

Hello

i am getting into a issue when running gatsby build: Cannot read property 'childImageSharp' of null

success run queries - ...
failed Building static HTML for pages - ...s

 ERROR #95313 

Building static HTML failed for path "/..."

See our docs page for more info on this error: https://gatsby.dev/debug-html

  WebpackError: TypeError: Cannot read property 'childImageSharp' of null
  
  - build-html.js:110 doBuildPages
    [pages]/[gatsby]/dist/commands/build-html.js:110:24
  
  - build-html.js:124 async buildHTML
    [pages]/[gatsby]/dist/commands/build-html.js:124:3
  
  - build.js:200 async build
    [pages]/[gatsby]/dist/commands/build.js:200:5
  

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `gatsby build --prefix-paths`

Steps to reproduce:

  1. Create gatsby page with markdowns with paths to file in frontmatter
  2. First build without cache to create the cache
  3. Modify the source markdown in any way. For example add empty line. The modification must trigger onCreateNode
  4. Second build with cache from step 2.

As the result WebpackError: TypeError: Cannot read property 'childImageSharp' of null is thrown.

After deep dive into function fmImagesToRelative i realize that array fileNodes did not contain any node (except one), because onCreateNode was call exactly ones for modified markdown.

fileNodes.push(node);

As work around y must register all nodes before first call of fmImagesToRelative

let isRegister = true

exports.onCreateNode = ({ node, getNodes }) => {
	if(isRegister) {
		const nodes = getNodes()
		nodes.forEach(node => fmImagesToRelative(node))
		isRegister = false
	}

	fmImagesToRelative(node); // convert image paths for gatsby images
	// ...
};

Error: No matching file found

After I upgraded to v2.0, gatsby build is throwing this error. For some reason, it is adding 'static' twice in the file path. I am not using any custom options in the gatsby config file. The build works if I downgrade to v1.

"gatsby-plugin-mdx" threw an error while running the onCreateNode lifecycle:

No matching file found for src "/static/e74f7be9122eaf7ab2744068d022888c/16546/add-calendar-events.png" in static folder "static". Please check static folder name and that file exists at "static/static/e74f7be9122eaf7ab2744068d022888c/16546/add-calendar-events.png". This error will probably cause a "GraphQLDocumentError" later in build. All converted field paths MUST resolve to a matching file in the "static" folder.

Error: No matching file found for src "/static/e74f7be9122eaf7ab2744068d022888c/16546/add-calendar-events.png" in static folder "static". Please check static folder name and that file exists at "static/static/e74f7be9122eaf7ab2  744068d022888c/16546/add-calendar-events.png". This error will probably cause a "GraphQLDocumentError" later in build. All converted field paths MUST resolve to a matching file in the "static" folder.
  
  - index.js:32 Object.exports.findMatchingFile
    [domain.com]/[gatsby-remark-relative-images]/dist/index.js:32:15
  
  - index.js:68 Node.<anonymous>
    [domain.com]/[gatsby-remark-relative-images]/dist/index.js:68:34
  
  - traversing.js:300 initialize.exports.each
    [domain.com]/[gatsby-remark-relative-images]/[cheerio]/lib/api/traversing.js:300:24
  
  - index.js:59 
    [domain.com]/[gatsby-remark-relative-images]/dist/index.js:59:18
  
  - Array.forEach
  
  - index.js:54 
    [domain.com]/[gatsby-remark-relative-images]/dist/index.js:54:56
  
  - Generator.next
  
  - index.js:8 
    [domain.com]/[gatsby-remark-relative-images]/dist/index.js:8:71
  
  - new Promise
  
  - index.js:4 __awaiter
    [domain.com]/[gatsby-remark-relative-images]/dist/index.js:4:12
  
  - index.js:36 exports.default
    [domain.com]/[gatsby-remark-relative-images]/dist/index.js:36:76
  
  - get-source-plugins-as-remark-plugins.js:59 transformer
    [domain.com]/[gatsby-plugin-mdx]/utils/get-source-plugins-as-remark-plugins.js:59:17
  
  - wrap.js:25 wrapped
    [domain.com]/[trough]/wrap.js:25:19
  
  - index.js:57 next
    [domain.com]/[trough]/index.js:57:24
  
  - wrap.js:55 done
    [domain.com]/[trough]/wrap.js:55:16
  
  - wrap.js:62 then
    [domain.com]/[trough]/wrap.js:62:5
  

not finished source and transform nodes - 78.261s
not finished Generating image thumbnails - 8.800s

(sharp:11509): GLib-CRITICAL **: 19:27:19.623: g_hash_table_lookup: assertion 'hash_table != NULL' failed

(sharp:11509): GLib-CRITICAL **: 19:27:19.624: g_hash_table_insert_internal: assertion 'hash_table != NULL' failed

(sharp:11509): GLib-CRITICAL **: 19:27:19.624: g_hash_table_lookup: assertion 'hash_table != NULL' failed
[1]    11508 segmentation fault  npm run build

Inline images src' in markdown body do not convert to relative paths.

Hi there @danielmahon,

Thank you loads for this nice functionality, yet I can't seem to figure out something. I am currently trying to render images in my Gatsby website from Netlify CMS. I am working with gatsby-remark-relative-images's 0.3.0 release and the images from my mdx frontmatter get picked up correctly by sharp and get rendered on my website with all percs of gatsby-image. This is due to using fmImagesToRelative(node) in gatsby-node.js: it transforms /media/image.png to ../../static/media/image.png.

Yet for the inline part of writing images in markdown - nothing happens at all. The paths of these stay exactly the same as reflected in my client. I tried upgrading your dependency to v2, but to no avail - it even stops converting my frontmatter image s paths to relative paths. Do you have any clue what is happening? Might it be related to our folder structure?:

-content
-static
  -media
-website

Matching algorithm for markdown images doesn't work

Hi, I was trying to use your plugin, but it was not working for me. So that's how I came up here 🙂
There is one part in the code that confuses me here.

const imagePath = slash(path.join(parentDirectory, node.url))
// See if there is a matching file path from gatsby-source-filesystem
const imageNode = _.find(files, file => {
   return slash(path.normalize(file.absolutePath)) === imagePath;
});

I have the following folders structure:
-content

  • blog
    • post.md
  • static
    • images
      • avatar.jpg

With this confition, imagePath would be content/blog/images/avatar.jpg.
And file of that image woule be static/images/avatar.jpg.
From my understanding, these two things will never be the same. And imageNode will always be undefined.
Could you please correct me if I'm wrong?

GraphQL Error Field must not have a selection since type "String" has no subfields.

Daniel, Thanks for your work on this module! I've been trying to get this setup over this weekend and just keep coming up against this error no matter what I have tried. This is undoubtedly user error on my end but I was hoping you might give a quick eye to my problem. Maybe you will see something quickly that I'm just missing.

https://github.com/BCOA/bcoa.com/blob/relativeImages/gatsby-node.js
https://github.com/BCOA/bcoa.com/blob/relativeImages/gatsby-config.js
Page / Collection Query: https://github.com/BCOA/bcoa.com/blob/relativeImages/src/templates/news.js#L100-L109
Test Data: https://github.com/BCOA/bcoa.com/blob/relativeImages/src/pages/articles/test.md

I come across this error in GraphiQL and when I run gatsby-develop

Any help would be appreciated!

Error: Unable to find plugin "gatsby-remark-relative-images" even after installing multiple versions

I've been trying to install and use this plugin, but regardless of what I do, the module reports as missing.

I have:

  • verified it's in node_modules directory
  • tried installing different versions of the modules
  • tried deleted node_modules and reinstalled everything

This is what the start of the modules config in my gatsby-config.js looks like:

  plugins: [
    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/content/uploads`,
        name: "assets",
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/content/blog`,
        name: "posts",
      },
    },
    `gatsby-plugin-sharp`,
    `gatsby-plugin-netlify-cms`,
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          `gatsby-remark-relative-images`,
          `gatsby-remark-copy-linked-files`,
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 605,
            },
          },
          "gatsby-remark-prismjs",
          `gatsby-remark-autolink-headers`,
        ],
      },
    },

Any ideas?

Field "image" must not have a selection since type "String" has no subfields.

I'm getting this error (not on windows) and couldn't fix it with many attempts. I looked at the other issues, but could not find a working solution...

Are things in the right order?

My gatsby-config.js

const path = require("path");

module.exports = {
  siteMetadata: {
    title: "Crisp Studio Blog",
    description: "Our Blog",
    siteUrl: "https://blog.crisp.studio"
  },
  mapping: {
    "MarkdownRemark.frontmatter.author": "AuthorYaml"
  },
  plugins: [
    {
      // keep as first gatsby-source-filesystem plugin for gatsby image support
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/static/assets`,
        name: "assets"
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/content`
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "content",
        path: `${__dirname}/src/content/posts`
      }
    },
    "gatsby-transformer-sharp",
    "gatsby-plugin-sharp",
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-relative-images`
          },
          {
            resolve: "gatsby-remark-images",
            options: {
              maxWidth: 1170,
              quality: 100
            }
          },
          {
            resolve: "gatsby-remark-responsive-iframe",
            options: {
              wrapperStyle: "margin-bottom: 1rem"
            }
          },
          "gatsby-remark-prismjs",
          "gatsby-remark-copy-linked-files",
          "gatsby-remark-smartypants",
          "gatsby-remark-abbr"
        ]
      }
    },
    "gatsby-plugin-netlify-cms",
    "gatsby-transformer-json",
    {
      resolve: "gatsby-plugin-canonical-urls",
      options: {
        siteUrl: "https://blog.crisp.studio"
      }
    },
    "gatsby-plugin-emotion",
    "gatsby-plugin-typescript",
    "gatsby-plugin-react-helmet",
    "gatsby-transformer-yaml",
    "gatsby-plugin-feed",
    {
      resolve: "gatsby-plugin-postcss",
      options: {
        postCssPlugins: [
          require("postcss-color-function"),
          require("cssnano")()
        ]
      }
    },
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        trackingId: "UA-XXXX-Y",
        // Puts tracking script in the head instead of the body
        head: true,
        // IP anonymization for GDPR compliance
        anonymize: true,
        // Disable analytics for users with `Do Not Track` enabled
        respectDNT: true,
        // Avoids sending pageview hits from custom paths
        exclude: ["/preview/**"],
        // Specifies what percentage of users should be tracked
        sampleRate: 100,
        // Determines how often site speed tracking beacons will be sent
        siteSpeedSampleRate: 10
      }
    }
  ]
}

The query in gatsby-node.js

 {
      allMarkdownRemark(
        limit: 2000
        sort: { fields: [frontmatter___date], order: ASC }
        filter: { frontmatter: { draft: { ne: true } } }
      ) {
        edges {
          node {
            excerpt
            timeToRead
            frontmatter {
              title
              tags
              date
              draft
              image {
                childImageSharp {
                  fluid(maxWidth: 3720) {
                    aspectRatio
                    base64
                    sizes
                    src
                    srcSet
                  }
                }
              }
[...]

Not updating raw html nodes when using gatsby-plugin-mdx

I noticed that the following does not work for mdx files in Gatsby

  // Process all HTML images in markdown body
  selectAll('html', markdownAST).forEach((_node: any) => {

Does it make sense to update it to the below?

  // Process all HTML images in markdown body
  selectAll('html, jsx', markdownAST).forEach((_node: any) => {

GIF image

Hello, I'm using the plugin gatsby-remark-relative-images. Everything is working well. All the image (jpg) are well converted to relative path. Except when I have a GIF image instead of JPG into markdown content. Then the relative path doesn't work. Has anyone encountered this issue?

Getting 'No matching file found for src "/img/concert.jpg" in static folder "static" '

When I run gatsby develop I get an error that says:

"gatsby-remark-relative-images" threw an error while running the onCreateNode lifecycle:

No matching file found for src "/img/concert.jpg" in static folder "static". Please check static folder name and that file
exists at "static/img/concert.jpg". This error will probably cause a "GraphQLDocumentError" later in build. All converted field
paths MUST resolve to a matching file in the "static" folder.

The problem is that there isn't any /img/ folder in my static folder, the subfolder is called assets (previously was called img but I needed to change the name).
My config.yml :

# ...
media_folder: static/assets
public_folder: /assets
# ... 

My gatsby-config.js :

plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `post_images`,
        path: `${__dirname}/static/assets`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/src/pages`,
      },
    },
    `gatsby-transformer-sharp`,
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-relative-images`,
            options: {}
          }
        ]
      }
    },
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-image`,
    `gatsby-plugin-gatsby-cloud`,
    `gatsby-plugin-netlify-cms`
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.dev/offline
    // `gatsby-plugin-offline`,
  ]

How do I solve this?

Resolve query despite image doesn't exist anymore

I had a view cases where customers deleted images from netlify-cms media folder without deleting the connected entry. So the markdown file still has the path to the image but the image doesn't exist anymore and the build then fails. Is there a fallback solution this plugin giving a null value if that case happens? thanks in advance

gatsby-remark-relative-images fails to process picturestook with DSLR

Hi! I'm trying to migrate my blog to gatsby. I migrated my posts to markdown and I uploaded to my gatsby. I installed gatsby-remark-relative-images to process my images relatively and it worked fine with most of images. But, gatsby-remark-relative-images fails to process picture that are took from DSLR. I think gatsby-remark-relative-images has bug that can't process high-quality images because of size of the images. Is there any option that I can make gatsby-remark-relative-images to process high-quality images or is it just a bug?

gatsby-remark-relative-images fails to process left image in picture .

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.