progital / gatsby-wpgraphql-inline-images Goto Github PK
View Code? Open in Web Editor NEWSolution for Gatsby and WPGraphQL sourced content. Downloads images locally.
License: MIT License
Solution for Gatsby and WPGraphQL sourced content. Downloads images locally.
License: MIT License
import { useStaticQuery, graphql } from 'gatsby'
export const useContentPlaceholder = () => {
const { wpgraphql } = useStaticQuery(graphqlquery useContentPlaceholderQuery { wpgraphql { post(id: "cG9zdDoxMzM=") { content } } }
)
return wpgraphql.post.content
}
import React from 'react'
import contentParser from 'gatsby-wpgraphql-inline-images'
import { useContentPlaceholder } from '../../hooks/useContent'
export default () => {
const content = useContentPlaceholder()
const pluginOptions = {
wordPressUrl: `https://noh.progital.dev/`,
uploadsUrl: `https://noh.progital.dev/wp-content/uploads/`,
}
return (
<React.Fragment>
{<div>{contentParser({ content }, pluginOptions)}</div>}
</React.Fragment>
)
}
I test across multiple different wordpress domains and even the example domain provided and the inline images are not being saved locally and converted into gatsby images. Am I doing something wrong here?
It seems to me that the plugin is configured as expected, with the headers authorization in its place:
gatsby-config.js
{
resolve: 'gatsby-wpgraphql-inline-images',
options: {
debugOutput: true,
wordPressUrl: 'https://admin.my-wordpress-site.com/',
uploadsUrl: 'https://admin.my-wordpress-site.com/wp/wp-content/uploads/',
processPostTypes: ['Page', 'Post'],
graphqlTypeName: 'WordPressGraphQl',
httpHeaders: {
Authorization: `Basic ${process.env.TOKEN_HTPASSWD}`,
},
},
},
After that I'm calling the plugin inside the template of the page:
templates/pageLayout.js
const pluginOptions = {
wordPressUrl: `https://admin.my-wordpress-site.com/`,
uploadsUrl: `https://admin.my-wordpress-site.com/wp/wp-content/uploads/`,
}
const content = data.wpGraphQl.page.content
[...]
<Layout>
<main>
<div>
<h1 dangerouslySetInnerHTML={{ __html: data.wpGraphQl.page.title }} />
<div>{contentParser({ content }, pluginOptions)}</div>
[...]
The content is well rendered but the image markups it the same as when I use dangerouslySetInnerHTML
:
<img
class="aligncenter size-large wp-image-240"
src="https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003-1024x768.jpg"
alt=""
srcset="https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003-1024x768.jpg 1024w, https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003-300x225.jpg 300w, https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003-768x576.jpg 768w, https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003.jpg 1200w" sizes="(max-width: 848px) 100vw, 848px" width="848" height="636">
(obviously the image is not displayed because the headless wordpress cms its protected by the htpasswd)
I presume that the images are not downloaded since I don't found them in the static folder.
This is the end part of the develop process in the shell when I activate debugOutput
:
success run static queries - 1.296 s — 5/5 3.95 queries/second
>>> Entered contentResolver @ URI not defined, skipping
success Downloading remote files — 1/1 - 0.461 s
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
success Downloading remote files — 4/4 - 1.383 s
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
success Downloading remote files — 1/1 - 0.252 s
success run page queries - 3.981 s — 13/13 3.29 queries/second
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
success start webpack server - 2.393 s — 1/1 2.45 pages/second
DONE Compiled successfully in 9911ms
Adding tests is something that I've been wanting to do for some time. This and re-organizing codebase to make it more testable is at the top of the list.
Hi there!
I'm getting the following error message for all my image requests when firing up gatsby develop
.
My local WP site is proxying the images from production, so not sure if that has anything to do with my issue. However, I was able to reproduce the issue on a fresh gatsby-hello-world and a fresh wp install with a local image.
Exception featured image TypeError: Cannot read property 'toLowerCase' of undefined
at healOptions (/node_modules/gatsby-plugin-sharp/plugin-options.js:51:38)
at fluid (/node_modules/gatsby-plugin-sharp/index.js:296:19)
at convertFileNodeToFluid (/node_modules/gatsby-wpgraphql-inline-images/src/utils.js:78:27)
at downloadImage (/node_modules/gatsby-wpgraphql-inline-images/src/utils.js:60:29)
at processTicksAndRejections (internal/process/task_queues.js:85:5)
at async Object.featuredImageResolver [as resolve] (/node_modules/gatsby-wpgraphql-inline-images/gatsby-node.js:102:19)
at async Promise.all (index 2)
at async Promise.all (index 0)
at async Promise.all (index 0)
query
query {
wordpress {
portfolios {
nodes {
title
featuredImage {
srcSet
sizes
sourceUrl
content
}
}
}
}
}
I'm using the plugin and I'm not seeing a way to use the traced svg or webp options. Those are really nice features that come with gatsby-image. Is there a plan to add more options?
Amazing plugin, but I did notice it doesn't work with anchor tags, any plans to incorporate?
I've just updated WPGraphql to the latest version 0.10.0
I'm getting this error:
Fragment "GatsbyImageJobQuery" cannot be spread here as objects of type "NodeWithFeaturedImageToMediaItemConnectionEdge" can never be of type "MediaItem".
Here my fragment:
fragment GatsbyImageJobQuery on WPGraphQL_MediaItem {
altText
sourceUrl
imageFile {
childImageSharp {
fixed(width: 120, height: 120) {
srcSetWebp
tracedSVG
...GatsbyImageSharpFixed
}
}
}
}
got some errors like Error: Unable to find plugin "gatsby-wpgraphql-inline-images". Perhaps you nee d to install its package?
and An unexpected error occurred: "could not find a copy of gatsby to link in
after I ran in terminal (copy/paste) command from this page:
https://www.gatsbyjs.org/packages/gatsby-wpgraphql-inline-images/
Hi,
The downloadImage function is included in utils.js
But is not referenced in the readme, or used within the plugin. Is this an oversight, or is it to be used in a future version? I am working through a problem I am having with the package and came across it.
Cheers
Before I had this plugin I was getting normal urls and string replacing "https://my.domain.com"
with ""
.
The plugin seems to be mangling URLs on menu Items to be localhost:8000/https:/pwddev.kinsta.cloud/video-testimonials/
Notice the missing /
on https://
Hi,
I am using your plugin for my build, and am unable to swap images out using the contentParser. After tracing the issue back it seems that there is no URI key on the source object passed from WordPress:
This means all the content is returned without being run through the sourceParser.
What is the reason for checking for a URI? Where is this set in WordPress?
When I remove the URI checker, I end up getting errors from createRemoteFileNode within the utils.js file:
Error:
Parameter passed to createNodeId must be a String or Number (got undefined)
Any ideas what this could be?
Thanks
The point at which URLs are converted only works on HTTPS
It may be better to use:
let elementUrlNoProtocol = elementUrl.replace(/(^\w+:|^)\/\//,'')
Thoughts?
When managing in a standard Gatsby query, a key 'toFormat: PNG' would be added to ensure that PNGs do not lose their transparency. Otherwise this happens:
This is caused by a webp image being created - losing transparency, and loading over the transparent PNG image.
In this instance we cannot do that. However, I think we can conditionally stop the webp being generated.
I am guessing that a check on the file type needs to occur, and then stop here:
Hi,
After running some tests, I have found that the resolver seems to be turning
entities into strings, meaning contentParser is making them visible to the end user.
I think this is due to Cheerio not decoding entities:
I can understand the confusion as here: https://cheerio.js.org/ the documentation says that decodeEntitites defaults to true, however looking at the in-depth documentation shows it actually defaults to false: https://github.com/fb55/htmlparser2/wiki/Parser-options#option-decodeentities
I am happy to add a PR unless there is a reason you have not included this?
Thanks
Hey!
I notice in the contentParser
it looks like it's looking for particular data attributes that I don't recognize.
For example here:
It's looking for elements with: attribs[data-gts-swapped-href]
Is there a WordPress plugin that is affecting image markup as well? Or what's going on with these custom attributes.
Just curious if there's anything needed on the WordPress side to work with this.
Thanks!
When rendering a table using the parser, the console returns the following error: Whitespace text nodes cannot appear as a child of <table>. Make sure you don't have any extra whitespace between tags on each line of your source code.
.
This does not appear when using a standard dangerouslySetInnerHTML implementation.
This package came across the issue and seemed to fix it: aknuds1/html-to-react#79
Also seems to be the most up-to-date.
Hello,
I'm trying to add the plugin to an install.
It tells me
error An unexpected error occurred: "could not find a copy of gatsby to link in /mnt/c/Users/USERSESSION/SITENAME/node_modules/gatsby-wpgraphql-inline-images/node_modules".
Adding other plugins works normally.
My repo is there if needed https://github.com/bonakor/nuuksby/
Let me know if I can give more infos :)
Hi,
When content is parsed from the editor it is removing anchor links.
Within the WordPress I have content that is set up like:
<a href="#what-is-an-actor">What is an Actor?</a>
However, when this is run through the parser the content is returned as:
<a class=" css-0" href="/">What is an Actor?</a>
On top of this, it seems to be added unneeded CSS classes.
I think these issues are caused the following line:
https://github.com/progital/gatsby-wpgraphql-inline-images/blob/dev/src/contentParser.js#L84
What is the need for using theme-ui, will a plain Link component not do the job?
Thanks,
Rob
Gatsby version >= 2.22.00
Rest of versions in package.json: https://github.com/louiechristie/newcrossities/blob/559b283e6f0e1a91d51639d7b0a47e37a1c689a1/package.json
yarn
error An unexpected error occurred: "could not find a copy of gatsby to link in /[project folder]/node_modules/gatsby-wpgraphql-inline-images/node_modules"
yarn
You've hand rolled handing remote images/files but this is native in gatsby APIs. I might have time to work on this but no promises :). Thanks for you efforts on this so far!
https://www.gatsbyjs.org/docs/schema-customization/#feeding-remote-images-into-gatsby-image
https://dev.to/nevernull/gatsby-with-wpgraphql-acf-and-gatbsy-image-72m
The plugin is not able to download any images from WP sites behind basic auth, or that require specific header tokens to access files.
WpGraphQL currently does this by allowing a headers option to be passed in via the config file. This may be the best way of doing this?
This header variable can then be passed to the CreateRemoteFileNode function.
See: HTTP Headers in the CreateRemoteFleNode documentation: https://www.gatsbyjs.org/packages/gatsby-source-filesystem/#createremotefilenode
Inline images are displaying correctly in development environment, but inline images are missing when building and deploying to a sub-folder.
Gatsby allows this by setting the pathPrefix
configuration option in gatsby-config.js
.
My guess is the plugin isn't using the withPrefix
function, which is explained in the following article Adding a Path Prefix.
I'm still investigating, where the /static
path is being set...might not be in this plugin. Any advice is appreciated.
Hey,
for your information im new to Gatsby and trying to render a static site with static files.
I have problems handling images in Gutenberg Blocks.
I queried the content I need via graphql and passed it through the contentParser function. But it didn't download the images as static files and returns nothing + there's no error.
Here's an insight to my syntax
import contentParser from 'gatsby-wpgraphql-inline-images'
const pluginOptions = {
wordPressUrl: 'http://cms-gatsby-project.local',
uploadsUrl: 'https://cms-gatsby-project.local/wp-content/uploads/'
}
const IndexPage = ({ data }) => {
return (
<div>{contentParser(data.wordpress.pages.nodes[0].content,pluginOptions)}</div>
)
}
export const pageQuery = graphql`
query frontPageQ{
wordpress {
pages(where: {name: "Startseite"}) {
nodes {
id
content
}
}
}
`
export default IndexPage
Hopefully you can help me :)
Hello!
I'm using this awesome plugin to render content and when I try to test my component using gatsby-wpgraphql-inline-images - it throws an error. I'm wondering if you can give guidance on how to correctly setup my test? Thanks!
FAIL src/templates/__tests__/supportQuestionPage.test.tsx
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/me/Documents/github/etShop-gatsby/node_modules/gatsby-wpgraphql-inline-images/src/contentParser.js:2
import { jsx } from "theme-ui"
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (node_modules/gatsby-wpgraphql-inline-images/index.js:1:45)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Here is what my component looks like:
import React from 'react'
import { graphql } from 'gatsby'
import contentParser from 'gatsby-wpgraphql-inline-images'
const SupportItem = (props: any) => {
const pluginOptions = {
wordPressUrl: `${process.env.GATSBY_DB}`,
uploadsUrl: `${process.env.GATSBY_DB}/wp-content/uploads/`
}
const {
// location,
pageContext: {
content
},
data: {
wpgraphql: { supportQuestion: { title } }
}
} = props
return (
<div>
<h1 data-testid={'title'}>{title}</h1>
<div data-testid={'content'}>
{contentParser({ content }, pluginOptions)}
</div>
</div>
)
}
export default SupportItem
And here is what the test looks like:
import React from 'react'
import {
render,
cleanup
} from 'react-testing-library'
import SupportItem from '../supportQuestion'
import { StaticQuery } from 'gatsby'
import { SupportQuestionOne, SupportQuestionPageQuery } from '@redux/reduxTestUtils'
beforeEach(() => {
// @ts-ignore
StaticQuery.mockImplementationOnce((mock) =>
mock.render(SupportQuestionPageQuery)
)
})
afterEach(cleanup)
describe('Support Question Page', () => {
it('Should render 1 Category', () => {
const modalRender = render(<SupportItem
data={SupportQuestionPageQuery}
pageContext={{ content: SupportQuestionOne.content }}
/>)
expect(modalRender.getByTestId('content').innerHTML).toBe(SupportQuestionOne.title)
})
})
gatsby develop
doesn't return errors but my template pages don't have any image.
I try the method explained on the readme:
const pluginOptions = {
wordPressUrl: `https://admin.mywordpress.domain/`,
uploadsUrl: `https://admin.mywordpress.domain/wp/wp-content/uploads/`,
};
const content = data.wpGraphQl.page.content
and then:
<div>{contentParser({ content }, pluginOptions)}</div>
In the content rendered the text is ok, but images are not rendered, only their at all.
The browser console neither returns errors.
The only strange error was noted on my IDE (vscode) that tells me this (in a message by the import contentParser):
import contentParser from 'gatsby-wpgraphql-inline-images';
Non è stato trovato alcun file di dichiarazione per il modulo 'gatsby-wpgraphql-inline-images'.
Trynpm install @types/gatsby-wpgraphql-inline-images
if it exists or add a new declaration (.d.ts) file containingdeclare module 'gatsby-wpgraphql-inline-images';
ts(7016)
This is my config on gatsby-config
:
{
resolve: 'gatsby-wpgraphql-inline-images',
options: {
wordPressUrl: 'https://admin.mywordpress.domain/',
uploadsUrl: 'https://admin.mywordpress.domain/wp/wp-content/uploads/',
processPostTypes: ['Page', 'Post'],
graphqlTypeName: 'WordPressGraphQl',
httpHeaders: {
Authorization: `Basic ${process.env.TOKEN_HTPASSWD}`,
}
},
},
the content has images from external url besides the wordpress upload, how to deal with that?
The content parser replaces WordPress <a />
with Gatsby's <Link />
, uses Styled.a
from theme-ui
. theme-ui
extends styled-system
, which seems to expect a ThemeProvider
to be configured. My project doesn't use or need theme-ui
or styled-system
, so when I call contentParser
; I get a long, confusing stack trace.
gatsby-wpgraphql-inline-images/src/contentParser.js
Lines 66 to 68 in 246a4d5
theme-ui
, styled-system
) are not really required for gatsby-wpgraphql-inline-images
to operate correctly. Would you be interested in removing them as dependencies? I'm happy to open a pull request.
Edit: typo fix
Hi there, can you confirm that the scope of this utility is limited to the default "Content" field that comes with Wordpress Post and Page post types, including CPTs that utilize the built in Content field?
I did some brief testing on a CPT that I have that ignores the built-in Content field, but instead uses the ACF Flexible Content field to create a Layout that uses a WYSIWYG field.
For all intents and purposes, the functionality on the CMS side looks the same, but my graphql queries would be further nested such as:
fragment OneColumnContentFields on Wordpress_LandingPage_Landingpagefields_Content_OneColumnContent {
background {
...
}
content
}
query GET_LANDING_PAGE($id: ID!) {
wordpress {
landingPage(id: $id) {
id
uri
title
landingPageFields {
content {
__typename
...OneColumnContentFields
}
}
}
}
}
Doesn't appear that the plugin will pick up the ACF WYSIWYG field thats nested inside of Flexible Content. Not sure if this is a bug or simply not intended functionality.
Hi,
I'm trying to install the plugin with W10, and it fails saying An unexpected error occurred:
\\node_modules".```
When I install the plugin with npm, it works but then launching "gatsby develop" bugs, saying
`Something went wrong installing the "sharp" module
Cannot find module '../build/Release/sharp.node'
Would you have an idea of what to do (but I'm guessing your plugin might be merged into the new version of GatsbyWp :/)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.