【发布时间】:2021-07-16 02:28:33
【问题描述】:
我正在尝试使用 Gatsby Node 和 Sharp transformer 管道将 JSON 文件中的图像加载到 GraphQL 中。内容节点已创建,但缺少 childImageSharp 和 gatsbyImageData 属性,这让我相信我的设置有问题。
我在 Github 上创建了一个最小示例以使问题可重现:https://github.com/stekhn/gatsby-image-sourcing
项目结构
src
├── data
│ └── projects.json
├── images
│ └── projects
│ ├── adam-vradenburg-sWAAhaoVuko-unsplash.jpg
│ ├── radek-homola-RfTD9NoLMEE-unsplash.jpg
│ ├── steven-kamenar-MMJx78V7xS8-unsplash.jpg
│ ├── will-tarpey-82pi_nJbE5M-unsplash.jpg
│ └── wolfgang-hasselmann-ZM4IxIcF9AU-unsplash.jpg
└── pages
├── 404.js
└── index.js
package.json
{
"name": "gatsby-image-sourcing",
"dependencies": {
"gatsby": "^3.3.1",
"gatsby-plugin-image": "^1.3.1",
"gatsby-plugin-sharp": "^3.3.1",
"gatsby-source-filesystem": "^3.3.0",
"gatsby-transformer-sharp": "^3.3.0",
"react": "^17.0.1",
"react-dom": "^17.0.1"
}
}
gatsby-config.js
module.exports = {
siteMetadata: {
title: "Gatsby Image Sourcing",
},
plugins: [
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images/projects/`,
},
},
],
};
gatsby-node.js:
const path = require("path");
const projects = require("./src/data/projects.json");
// Reference: https://stackoverflow.com/a/56012718
exports.sourceNodes = ({ actions, createNodeId, createContentDigest }) => {
projects.forEach((project) => {
const { title, year, tags, image } = project;
const { name, ext } = path.parse(image);
const absolutePath = path.resolve(
__dirname,
"src/images/projects",
image
);
const imageData = {
name,
ext,
absolutePath,
extension: ext.substring(1),
};
console.log(imageData);
const imageNode = {
...imageData,
id: createNodeId(`project-card-image-${name}`),
internal: {
type: "projectCardsImage",
contentDigest: createContentDigest(imageData),
},
};
actions.createNode(imageNode);
const node = {
title,
year,
tags,
image: imageNode,
id: createNodeId(`project-card-${title}`),
internal: {
type: "projectCards",
contentDigest: createContentDigest(project),
},
};
actions.createNode(node);
});
};
projects.json
[
{
"title": "Project 1",
"year": "2021",
"tags": ["foo", "bar"],
"image": "adam-vradenburg-sWAAhaoVuko-unsplash.jpg"
}
]
图像路径看起来不错,并且 gatsby-node.js 运行没有问题。然而,当我在 GraphiQL 资源管理器中检查 projectCards 和 projectCardsImage 时,Gatsby Transformer Sharp 似乎从未运行过。通常,我希望看到属性childImageSharp 成为image 的一部分。
我很清楚还有其他加载和使用图像的方法,它们都可以正常工作。但是现在,我有点赞同使用 Gatsby Node 来填充 GraphQL 数据库的确切类型的对象,我需要在我的组件中。
参考文献
- How to load a local image on a gatsby source plugin?
- https://freddydumont.com/blog/how-to-source-images-and-data-from-json-files-in-gatsby
非常感谢任何帮助。
【问题讨论】:
标签: gatsby gatsby-image