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:
gatsby-node.js: It make possible to build Gatsby.
gatsby-config.js: used for configuration and setup.
gatsby-browser.js: It allow Plugin to run code in the browser.
gatsby-ssr.js: It adds functionality to the server-side rendering (SSR) process.
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!
댓글