9

Handling Images in Gatsby with High Performance

 4 years ago
source link: https://scotch.io/tutorials/handling-images-in-gatsby-with-high-performance
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

Table of Contents

  • Installation of Node.js and Gatsby.js
  • Creation of Cloudinary Account
  • Creation of New Gatsby Project
  • Installation of Additional Packages
  • Configuration of gatsby-config.js
  • Creation of Image Gallery
  • Deployment to Netlify

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.

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

  • You can declaratively query Cloudinary’s media assets alongside other application data with GraphQL.
  • Cloudinary delivers media assets through a content delivery network (CDN), reducing the app- bundle size on build.
  • Gatsby-Source-Cloudinary automatically optimizes the quality and format of the media files delivered by 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.

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 -v && npm -v

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

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

Essential Reading : Learn React from Scratch! (2020 Edition)
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.

Afterwards, do the following:

gallery

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 new cloudinary-site

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

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.

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

s_F2DB697C20DB2900E952897A6582F157DAE4391AB0ADA1EBD0D8E2F67307CC1F_1579732344697_image.png

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.
  • The [gatsby-source-cloudinary](https://www.npmjs.com/package/gatsby-source-cloudinary) plugin: for fetching optimized images from Cloudinary.

Install them with npm by typing this command line:

npm i --save dotenv gatsby-source-cloudinary

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:

  1. Import the dotenv file you installed earlier to the gatsby-confi.js file and add the gatsby-source-cloudinary plugin with this code:
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:
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:

s_F2DB697C20DB2900E952897A6582F157DAE4391AB0ADA1EBD0D8E2F67307CC1F_1579734262094_image.png

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

Creation of Image Gallery

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:
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:
.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:
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 .
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:

s_F2DB697C20DB2900E952897A6582F157DAE4391AB0ADA1EBD0D8E2F67307CC1F_1579735865260_gsc-sample.gif

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

gatsby build

Deployment to Netlify

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

  1. Push your code to a remote repository, such as GitHub or Bitbucket.
  2. Create a Netlify account and log in.
  3. Create a new project from your deployed repository on 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.
  5. Add the environment variables to the environment variables settings on Netlify. Omitting this step will cause the deployment to fail.
  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:

s_F2DB697C20DB2900E952897A6582F157DAE4391AB0ADA1EBD0D8E2F67307CC1F_1579736874654_image.png

For the complete code, see its GitHub repository .

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.

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!

Like this article? Follow @iChuloo on Twitter

This content is sponsored via Syndicate Ads .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK