I'm trying to create a static site with GatsbyJS and I need to resolve the img tags so that relative URLs point to a certain directory, while absolute ones (which start with http(s):// work normally).
I've tried making a proper component, but since it's not a page, Graphql won't run:
import React from "react"
import { graphql } from "gatsby"
// Component constants
const absUrlRex = new RegExp(/^https?:\/\//, "i")
// Component
const CustomImg = ({ src, data, ...props }) => {
let imgSrc = src
if (!absUrlRex.test(src)) {
if (null !== data.file) {
imgSrc = data.file.publicURL
} else {
console.log(`Image "${src}" NOT found!`)
}
}
return <img src={imgSrc} {...props} />
}
export default React.memo(
CustomImg,
(prev, next) => next.src === prev.src
)
export const query = graphql`
query($src: String!) {
file (
sourceInstanceName: {eq: "images"},
relativePath: {eq: $src}
) {
publicURL
}
}
`
I've already tried StaticImage of "gatsby-plugin-image", but the src parameter is not a static string, so it doesn't work.