gatsby_在Gatsby中高效处理图像

gatsby

Gatsby, an open-source tool for building high-performance JAMstack apps, boasts numerous plugins that extend its capabilities. For example, by leveraging source plugins in Gatsby, you can source data from multiple services, APIs, and even Excel spreadsheets.

Gatsby是用于构建高性能JAMstack应用程序的开源工具,拥有众多扩展其功能的插件。 例如,通过利用Gatsby中的源插件,您可以从多个服务,API甚至Excel电子表格中获取数据。

Cloudinary is a cloud-based, end-to-end media-management platform on which you can store, dynamically optimize, and responsively deliver images and videos for both desktop or mobile apps.

Cloudinary是一个基于云的端到端媒体管理平台,您可以在该平台上存储,动态优化和响应性地为台式机或移动应用提供图像和视频。

The Gatsby-Source-Cloudinary plugin fetches optimized media assets from a folder on Cloudinary in a Gatsby project. Additionally:

Gatsby-Source-Cloudinary插件从Gatsby项目中Cloudinary上的文件夹中获取优化的媒体资产。 另外:

  • You can declaratively query Cloudinary’s media assets alongside other application data with GraphQL.

    您可以使用GraphQL声明性地查询Cloudinary的媒体资产以及其他应用程序数据。
  • Cloudinary delivers media assets through a content delivery network (CDN), reducing the app- bundle size on build.

    Cloudinary通过内容交付网络(CDN)交付媒体资产,从而减少了构建应用程序捆绑包的大小。
  • Gatsby-Source-Cloudinary automatically optimizes the quality and format of the media files delivered by Cloudinary.

    Gatsby-Source-Cloudinary自动优化Cloudinary交付的媒体文件的质量和格式。

Thus, you have the best of two worlds: high-performance apps along with optimized delivery of media assets.

因此,您拥有两个世界中的最佳选择:高性能应用程序以及优化的媒体资产交付。

This tutorial steps you through the process of building a responsive image gallery with Gatsby and images from Cloudinary. Because Gatsby is written in React.js, you must have a working knowledge of JavaScript and React.js.

本教程将逐步指导您使用Gatsby和Cloudinary的图像构建响应式图像库。 由于Gatsby是用React.js编写的,因此您必须具有JavaScript和React.js的使用知识。

安装Node.js和Gatsby.js ( Installation of Node.js and Gatsby.js )

You need Node.js and its package manager, npm, for this project. To check if they’ve been installed on your system, type the following command in your terminal:

您需要此项目的Node.js及其程序包管理器npm。 要检查它们是否已安装在系统上,请在终端中键入以下命令:

node -v && npm -v

If the output show no version numbers, go to Nodejs.org to download and install Node.js, which ships with npm.

如果输出中没有显示版本号,请转到Nodejs.org下载并安装npm附带的Node.js。

Next, install the Gatsby.js CLI tool by typing this command in your terminal:

接下来,通过在终端中键入以下命令来安装Gatsby.js CLI工具:

npm install -g gatsby-cli

创建云账户 ( Creation of Cloudinary Account )

To source images from Cloudinary, you must first set up an account there. Cloudinary offers a generous, free tier account that’s largely adequate for starter projects and that scales with the project.

要从Cloudinary获取图像,您必须首先在该处设置 一个帐户 。 Cloudinary提供了一个慷慨的免费套餐帐户,该帐户在很大程度上适合于入门项目,并且可以随项目扩展。

Afterwards, do the following:

然后,执行以下操作:

  1. Upload the images for the image gallery to a folder in your media library on Cloudinary. Name the folder with a name of your choice, e.g., gallery.

    将图库的图像上传到Cloudinary上媒体库中的文件夹。 用您选择的名称命名文件夹,例如gallery
  2. Obtain your API key and API secret from your Cloudinary dashboard.

    从Cloudinary仪表板获取API密钥和API机密。

创建新盖茨比项目 ( Creation of New Gatsby Project )

Gatsby contains starters that quickly generate new projects with a base setup. To create a new Gatsby project in a folder of your choice with the default starter, type this command line:

Gatsby包含一些启动程序,这些启动程序可以通过基本设置快速生成新项目。 要使用默认启动器在您选择的文件夹中创建新的Gatsby项目,请键入以下命令行:

gatsby new cloudinary-site

Next, navigate to the project directory and start a new development server on http://localhost:8000 with this command:

接下来,导航到项目目录,并使用以下命令在http://localhost:8000上启动新的开发服务器:

cd cloudinary-site && gatsby develop

Because it contains GraphQL, Gatsby simultaneously creates a GraphQL IDE on http://localhost:8000/___graphql, with which you will build GraphQL queries later.

由于Gatsby包含GraphQL,因此它同时在http://localhost:8000/___graphql上创建了GraphQL IDE,稍后您将使用它来构建GraphQL查询。

Now go to http://localhost:8000 to see the new Gatsby project, which looks something like this:

现在转到http:// localhost:8000以查看新的Gatsby项目,该项目如下所示:

安装附加软件包 ( Installation of Additional Packages )

You need two other packages for this project:

您需要此项目的其他两个软件包:

  • The [dotenv](https://www.npmjs.com/package/dotenv) module: for loading environment variables from a .env file.

    [dotenv](https://www.npmjs.com/package/dotenv)模块:用于从.env文件加载环境变量。
  • The [gatsby-source-cloudinary](https://www.npmjs.com/package/gatsby-source-cloudinary) plugin: for fetching optimized images from Cloudinary.

    [gatsby-source-cloudinary](https://www.npmjs.com/package/gatsby-source-cloudinary)插件:用于从Cloudinary获取优化的图像。

Install them with npm by typing this command line:

通过键入以下命令行,使用npm安装它们:

npm i --save dotenv gatsby-source-cloudinary

gatsby-config.js的配置 ( Configuration of gatsby-config.js )

You configure all plugins, including those that accompany the default starter, in the gatsby-config.js file, which resides in the root directory of Gatsby projects. Do the following:

您可以在gatsby-config.js文件中配置所有插件,包括默认启动程序随附的插件,该文件位于Gatsby项目的根目录中。 请执行下列操作:

  1. Import the dotenv file you installed earlier to the gatsby-confi.js file and add the gatsby-source-cloudinary plugin with this code:

    将您先前安装的dotenv文件导入到gatsby-confi.js文件,并使用以下代码添加gatsby-source-cloudinary插件:
require('dotenv').config();

module.exports = {
  ...
  plugins:[
  ...
  {
      resolve: `gatsby-source-cloudinary`,
      options: {
        cloudName: process.env.CLOUDINARY_CLOUD_NAME,
        apiKey: process.env.CLOUDINARY_API_KEY,
        apiSecret: process.env.CLOUDINARY_API_SECRET,
        resourceType: `image`,
        prefix: `gatsby-source-cloudinary/` 
      }
    }
  ]
} 


`gatsby-source-cloudinary` takes these options:
- `**cloudName**`, `**apiKey**` , and `**apiSecret**`**:** These are credentials from your Cloudinary console, stored as three separate environment variables for security.
- `**resourceType**`**:** This is the resource type of the media assets: either an image or a video.
- `**prefix**`**:** This is the folder (in your Cloudinary account) in which the files reside. In the example above, I named this folder `gatsby-source-cloudinary` . Assign a name of your choice.


Other optional options are `type`, `tags`, and `maxResult`.
  1. In the root of your project, create an environment file called .env to which to add your Cloudinary credentials and their values, like this:

    在项目的根目录中,创建一个名为.env的环境文件,向其中添加您的Cloudinary凭据及其值,如下所示:
CLOUDINARY_API_KEY=xxxxxxxxxxxxxx
CLOUDINARY_API_SECRET=xxxxxxxxxxxxxxxxxxxx
CLOUDINARY_CLOUD_NAME=xxxxx


The `dotenv` package exposes those environment variables in the project.
  1. Restart the Gatsby development server to see the plugin in action, as in this example:

    重新启动Gatsby开发服务器以查看该插件的运行情况,如以下示例所示:

Note the `info` log, which displays the CloudinaryMedia nodes. Those images are ready to be queried in Gatsby components.

To create the image gallery:

要创建图片库:

  1. In the src/components folder, create a component file called ImageGallery.js and add the React functional component to the file, as follows:

    src/components文件夹中,创建一个名为ImageGallery.js的组件文件,并将React功能组件添加到该文件中,如下所示:
import React from 'react'
import './gallery.css'
import {useStaticQuery, graphql} from 'gatsby'
const ImageGallery = () => {
    const data = useStaticQuery(graphql`query CloudinaryImage {
            allCloudinaryMedia {
              edges {
                node {
                  secure_url
                }
              }
            }
          }`
    )
    const clImages = data.allCloudinaryMedia.edges
    return (
        <div>
          <div className="image-grid">
            {clImages.map((image, index) => (
                  <div className="image-item" key={`${index}-cl`}>
                    <img src={image.node.secure_url} alt={"no alt :("} />
                  </div>
                ))
            }
          </div>
        </div>
      )
  }
  export default ImageGallery


Here, you query all the Cloudinary images sourced into the `CloudinaryMedia` nodes with the `useStaticQuery` hook. In turn, you map through those image URLs to create a gallery with the component.
  1. Create a file called ./gallery.css in src/components for styling the component. Add the CSS styles to the file, as follows:

    src/components创建一个名为./gallery.css的文件来./gallery.css src/components的样式。 将CSS样式添加到文件中,如下所示:
.image-grid {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    grid-auto-rows: minmax(50px, auto);
  }
  .image-grid .image-item:nth-child(5n) {
    grid-column-end: span 2;
  }
  .image-grid img {
    display: flex;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }


The above styling renders your image gallery into a beautiful, responsive masonry grid.
  1. Replace the existing content of the index.js file in the src/pages folder with the newly created ImageGallery component, as follows:

    src/pages文件夹中index.js文件的现有内容替换为新创建的ImageGallery组件,如下所示:
import React from "react"
import Layout from "../components/layout"
import SEO from "../components/seo"
import ImageGallery from "../components/ImageGallery"
const IndexPage = () => (
  <Layout>
    <SEO title="Home" />
    <h1>Image Gallery</h1>
    <p>Here's a Gatsby site with optimized images in a masonry grid, served from <a href="https:cloudinary.com" target="_blank" rel="noopener noreferrer">Cloudinary</a></p>
    <div style={{ marginBottom: `1.45rem` }}>
      <ImageGallery/>
    </div>
  </Layout>
)
export default IndexPage


Gatsby automatically creates dynamic routes for single pages in the  `src/pages` folder, with `index.js` being the root or home page.
  1. Optional. Feel like tweaking the styles a bit? In the src/components/header.js file, change the background style property of the <header> element to #002954.

    可选的 。 想要稍微调整一下样式吗? 在src/components/header.js文件中,将<header>元素的background样式属性更改为#002954
You might also like to rewrite the site title, which is pulled from the site metadata specified in `gatsby-config.js`. Update the `title` property of `siteMetadata` to Gatsby-Cloudinary Image Gallery.

Now restart the development server and have a look at the updated page. Here’s an example:

现在,重新启动开发服务器,并查看更新的页面。 这是一个例子:

Next, create a deployable, optimized build by typing this command in your terminal:

接下来,通过在终端中键入以下命令来创建可部署的优化构建:

gatsby build

部署到Netlify ( Deployment to Netlify )

To deploy this JAMstack app to Netlify with a prebuilt continuous integration and continuous delivery (CI/CD) pipeline, follow these steps:

要将此JAMstack应用程序通过预先构建的持续集成和持续交付(CI / CD)管道部署到Netlify ,请执行以下步骤:

  1. Push your code to a remote repository, such as GitHub or Bitbucket.

    将您的代码推送到远程存储库,例如GitHub或Bitbucket。
  2. Create a Netlify account and log in.

    创建一个Netlify帐户并登录。
  3. Create a new project from your deployed repository on Netlify.

    从Netlify上已部署的存储库中创建一个新项目。
  4. Type the build command and build directory in the text fields, in this case gatsby build and public, respectively. In most cases, Netlify detects the technology and auto-populates those fields.

    在文本字段中输入build命令和build目录,在本例中分别为gatsby buildpublic 。 在大多数情况下,Netlify会检测技术并自动填充这些字段。
  5. Add the environment variables to the environment variables settings on Netlify. Omitting this step will cause the deployment to fail.

    将环境变量添加到Netlify的环境变量设置中。 省略此步骤将导致部署失败。
  6. Run the deployment and voila! Your image gallery has taken shape.

    运行部署,瞧! 您的图片库已成形。

Here’s the deployed version of this project.

这是该项目的部署版本

And here’s the lighthouse audit of the deployed website, which showcases the power of Gatsby and Cloudinary with eight high-resolution images delivered on the page you just created:

这是对已部署网站的灯塔审核,其中在刚创建的页面上提供了八张高分辨率图像,展示了盖茨比和Cloudinary的强大功能:

For the complete code, see its GitHub repository.

有关完整的代码,请参见其GitHub存储库

摘要 ( Summary )

Now that you’ve learned how to build an optimized and responsive image masonry with the Gatsby-Source-Cloudinary plugin on Cloudinary, you can apply the process to other websites and apps on the JAMstack architecture.

既然您已经了解了如何使用Cloudinary上的Gatsby-Source-Cloudinary插件来构建优化的,响应式的图像砌体,您就可以将该流程应用于JAMstack体系结构上的其他网站和应用程序。

Also, do check out the Gatsby-Transformer-Cloudinary plugin, with which you can upload media assets to Cloudinary and create file nodes off them, ready for use in the robust g``atsby-``i``mage component in React. Have fun!

另外,请检查一下Gatsby-Transformer-Cloudinary插件 ,您可以使用该插件将媒体资产上传到Cloudinary并在它们之上创建文件节点,以准备在React的强大g``atsby-``i``mage组件中使用。 玩得开心!

翻译自: https://scotch.io/tutorials/handling-images-in-gatsby-with-high-performance

gatsby

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值