• Whizzystack Solutions

Understanding Plugin Development In Gatsby



Gatsby is a React-based static-site generator that has huge tools to create website and blogs. It use plugins to create custom functionality which is not available at the time of installation.


Here I will discuss about the topic like-

  • Types of Gatsby plugins

  • Different forms of Gatsby plugins

  • Create a comment plugin for Gatsby website


What Is A Gatsby Plugin?


Gatsby is a static-site generator which can be use at anywhere. Plugins helps to extend Gatsby with the feature which is not available in the box. We can create a manifest.json file for a progressive web app (PWA), embedding tweets on a page, logging page views, and much more by Plugins.


Types of Gatsby Plugins


There are two types:


i) local- It can be develop in the project directly

ii) external- available through npm or Yarn or may be linked in the same computer by yarn link or npm link command


Forms of Gatsby Plugins


There are three types of Plugins:

  • Source plugins: This provide sources of data for a Gatsby website.

  • Transformer plugins: This helps to transfer data from source to other plugins in most easy and expected form.

  • Generic plugins: It can do the things which is not done by other two plugins.


Components of A Gatsby Plugin


Some files are important to create Gatsby:


Building a Comment Plugin For Gatsby


For developing a Gatsby plugin you need to create comment plugin which is installable.


Serving And Loading Comments


We need to provide a server to saving and loading comments. It accept the following fields of the

  • body-content: [string]

Which give comment to itself,

  • author: [string]

The name of the author of the comments

  • website

The website that the comment is being posted from,

  • slug

It is for the comment.


Integrating the Server With Gatsby Using API Files

  • Initializing the folder

It is a command line interface. Then change it into plugin directory to open it in code editor.

  • Installing axios for Network Requests

Axios package is installed to make web request.

  • Adding a New Node Type

A new node type is added to extend the comments.

  • Fetching Comments From the Comments Server

Axios is used to pull comments and store them to data layer.

  • Transforming Data (Comments)

To resolve comments on post we need an API.

  • Final Code for Comment Sourcing and Transforming

const axios = require("axios");
 
exports.sourceNodes = async (
 { actions, createNodeId, createContentDigest },
 pluginOptions
) => {
 const { createTypes } = actions;
 const typeDefs = `
 type CommentServer implements Node {
 _id: String
 author: String
 string: String
 website: String
 content: String
 slug: String
 createdAt: Date
 updatedAt: Date
 }
 `;
 createTypes(typeDefs);
 
 const { createNode } = actions;
 const { limit, website } = pluginOptions;
 const _limit = parseInt(limit || 10000); // FETCH ALL COMMENTS
 const _website = website || "";
 
 const result = await axios({
 url: `https://Gatsbyjs-comment-server.herokuapp.com/comments?limit=${_limit}&website=${_website}`,
 });
 
 const comments = result.data;
 
 function convertCommentToNode(comment, { createContentDigest, createNode }) {
 const nodeContent = JSON.stringify(comment);
 
 const nodeMeta = {
 id: createNodeId(`comments-${comment._id}`),
 parent: null,
 children: [],
 internal: {
 type: `CommentServer`,
 mediaType: `text/html`,
 content: nodeContent,
 contentDigest: createContentDigest(comment),
 },
 };
 
 const node = Object.assign({}, comment, nodeMeta);
 createNode(node);
 }
 
 for (let i = 0; i < comments.data.length; i++) {
 const comment = comments.data[i];
 convertCommentToNode(comment, { createNode, createContentDigest });
 }
};
 
exports.createResolvers = ({ createResolvers }) => {
 const resolvers = {
 MarkdownRemark: {
 comments: {
 type: ["CommentServer"],
 resolve(source, args, context, info) {
 return context.nodeModel.runQuery({
 query: {
 filter: {
 website: { eq: source.fields.slug },
 },
 },
 type: "CommentServer",
 firstOnly: false,
 });
 },
 },
 },
 };
 createResolvers(resolvers);
};

This is the final code .


Saving Comments as JSON File:


JSON File make possible to fetch data on demand.


Rendering Comments

  • Define the Root Container for HTML

We have to set HTML element to set the point in a page. It is expected to set every page have HTML point.

  • Implement the Route Update API in the gatsby-browser.js File

Fetching file and component should be done when file is visited.

  • Create Helper That Creates HTML Elements

Define function need to create element in HTML.

  • Create Header of Comments Section

We need to add header in the comment component.


Posting a Comment

  • Post Comment Form Helper

We need to make post request for the end point of API.

  • Append the Post Comment Form

Appending a form can be done by the code.

// ... helpers
exports.onRouteUpdate = async ({ location, prevLocation }, pluginOptions) => {
 const commentContainer = document.getElementById("commentContainer")
 if (commentContainer && location.path !== "/") {
 // insert header
 // insert comment list
 commentContainer.appendChild(createCommentForm())
 }
}

Test the Plugin


Create a Gatsby Website


A Gatsby website is done by following coding
// PARENT
// ├── PLUGIN
// ├── Gatsby Website
 
gatsby new private-blog https://github.com/gatsbyjs/gatsby-starter-blog

Conclusion


In this article we explain how to create Gatsby plugin. Here we learn that Plugin uses different APIs file to provide comments in Gatsby website. We can save comments in JSON files. Plugin made this post in npm module and full code in GitHub.


We will be happy to answer your questions on designing, developing, and deploying comprehensive enterprise web, mobile apps and customized software solutions that best fit your organization needs.

As a reputed Software Solutions Developer we have expertise in providing dedicated

remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to get in touch with us!

32 views

Recent Posts

See All
 You can unsubscribe in one click, and I will never share your email address.

About Whizzystack

  • LinkedIn
  • Facebook
  • Twitter
  • Instagram
  • RSS

We are User Experience Consultant, Conversion Rate Optimization Specialist and expert in digital transformation. We help savvy marketers, product owners and UX advocates make the case that a useable, accessible and people-first experience is the best path to business success. All the while pursuing his not-so-hidden agenda. We also build & support your own talented, trusted, full-time development team hosted out of Whizzystack’s headquarters in India. We also deliver world class product and software development services Read more

What We Do

Software Development

Web Application Development

Mobile Application Development Web Portal Development

Ecommerce Development

Custom Software Development

Web Presence

UI/UX Development

Digital Marketing

Social Media Management

Search Engine Optimization

Online Reputation Management

Web Experience

UI/UX Prototyping

System Designing

Service Designing 

System Integration

Performance Optimization

Our Developers

Contact Whizzystack

USA :     +1(877)3685420

India:    +91(95)60641297

              +91(120)4287309

111, Pemberton Brown Mills Road,

Brown Mills, New Jersey, USA, 08015

Bouleward Walk, Habitapur, Noida, Uttar Pradesh, India, 20109