【问题标题】:GatsbyJS - load multiple remote images and link to node - no ChildImageSharpGatsbyJS - 加载多个远程图像并链接到节点 - 没有 ChildImageSharp
【发布时间】:2020-02-22 07:13:58
【问题描述】:

我的设置是 GatsbyJS,将 Ghost 作为外部 CMS,我正在尝试在本地加载页面的所有图像。

所以我找到了一篇博文,向我展示了一种对一张图片执行此操作的方法,这对我有用:https://ghost.joonaviertola.com/optimize-ghost-images-in-gatsby/

然后我想我也可以对多个图像执行此操作,而不是将一个图像链接到节点,而是创建一个包含所有图像的数组。 我第一次尝试只为一张图片。直接链接图片,并将图片推送到节点上的数组中。

imgUrls = [...]; // list of absolute URLs of remote images
node.localImages = [];

// test with only one image first
if (imgUrls.length) {
    const fileNode = await createRemoteFileNode({
        url: imgUrls[0],
        store,
        cache,
        createNode,
        parentNodeId: node.id,
        createNodeId
    });

    if (fileNode) {
        node.localImage___NODE = fileNode.id;
        node.localImages.push(fileNode);
    }
}

在 GraphQL 资源管理器中,我现在看到了:

所以node.localImage___NODE = fileNode.id 正在工作,我将图像链接到节点,其中包含childImageSharp

node.localImages.push(fileNode) 另一方面似乎可以工作,因为我得到了一个数组,里面有一个图像(在这种情况下)。只有childImageSharpchildMarkdownRemark 丢失了,这是我想要开始的部分。

现在我不确定整个方法是否完全错误,或者我只是一步之遥。 有什么想法吗?

【问题讨论】:

    标签: gatsby gatsby-image


    【解决方案1】:
    exports.onCreateNode = async ({ node, getNode, actions, store, createNodeId, cache }) => {
        const { createNodeField, createNode } = actions;
        // Download image and create a File node with gatsby-transformer-sharp.
        if ([`GhostPost`, `GhostPage`].includes(node.internal.type)) {
            // Parse HTML and get all images
            if (node.html) {
                const regex = /<img.+?src="(.+?)".+?>/g;
    
                let imgUrls = [];
                let matches = regex.exec(node.html);
                while (matches) {
                    imgUrls.push(matches[1]);
                    matches = regex.exec(node.html);
                }
    
                const localImages = [];
    
                for (const imgUrl of imgUrls) {
                    if (!['.jpg', '.jpeg', '.png'].some(item => imgUrl.toLowerCase().includes(item))) {
                        continue;
                    }
    
                    const fileNode = await createRemoteFileNode({
                        url: imgUrl,
                        store,
                        cache,
                        createNode,
                        parentNodeId: node.id,
                        createNodeId
                    });
    
                    if (fileNode) {
                        localImages.push(fileNode.id);
                    }
                }
    
                node.localImages___NODE = localImages;
            }
        }
    };
    

    不确定这是否是正确/最佳的方法,但它现在似乎有效。 从 Ghost 中为每个帖子创建一个 GhostPost 节点,从 html 中提取所有图像(jpg 和 png),创建它们的图像节点并将它们链接到 GhostPost 节点。

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 1970-01-01
      • 2017-03-18
      • 2021-11-25
      • 2021-03-12
      • 2018-03-20
      • 2017-02-05
      • 2017-03-31
      • 2020-07-24
      相关资源
      最近更新 更多