Why Plop.js

Why I use plop in my project? Is it necessary when we have AI to generate snippet?

What is Plop.js?

Plop is small tool that provides a simple way to generate code or any other type of flat text files in a consistent way. As we follow some structure and pattern in the code; more over as In my project use content-layer to write my blog/article page we need to have md or mdx files with some meta tags.
Every time create with same structure is bit irritating. That is when plop came into the picture.

NOTE: More on plop you can follow official page its pretty well documented.

How to start with plop?

  1. Add plop yo your project
yarn add -D plop
  1. Create a plopfile in the root directory of the project
touch plopfile.js

To use this syntax, your plopfile must be either:

  • An ESM .js file with type: "module" in package.json
  • An ESM .mjs file with any type declared in package.json

If you CommonJS is followed in package.json better to use .cjs. If you are using the module system you can opt of .mjs.

  1. Create your first plop file.

A plopfile as a node module that exports a function which accepts the plop object as its first parameter.

export default function (
  /** @type {import('plop').NodePlopAPI} */
  plop
) {
  // create your generators here
  plop.setGenerator('template', {
    description: 'This is content template generator plop',
    prompts:[],
    actions:[]
  });
};

You can check more on how to create propmts and actions in the plop doc Plop uses the inquirer.js library to gather user data. A list of prompt types can be found on the inquirer official website.

Here sample the code snippet that I have written for my mdx template

plopfile.mjs
import { format } from 'date-fns';
 
const isNotEmpty = fieldName => value => String(value).length ? true : `${fieldName} is required!`
 
const prompts = [{
  name: 'template_type',
  type: 'list',
  message: 'Choose type of template',
  choices: [
    {
      name: 'Blog Template',
      value: 'blog',
      description: 'Template for the blog content',
    },
    {
      name: 'Project Template',
      value: 'project',
      description: 'Template for the project content',
    },
  ],
  loop: true
},
{
  type: 'input',
  name: 'name',
  message: 'Enter file name',
  validate: isNotEmpty('File name')
},
] // array of inquirer prompts
 
const actions = data => {
  const action_sequence = new Map()  // array of actions
 
  action_sequence.set('blog', [{
    type: 'add',
    path: 'content/blog/{{dashedName name}}.mdx',
    templateFile: 'plop-templates/blog.template.hbs'
  }])
 
  action_sequence.set('project', [{
    type: 'add',
    path: 'content/projects/{{dashedName name}}.mdx',
    templateFile: 'plop-templates/project.template.hbs'
  }])
 
  if (!action_sequence.has(data?.template_type))
    throw Error('invalid document template type')
 
  return action_sequence.get(data.template_type)
}
 
// eslint-disable-next-line import/no-anonymous-default-export
export default function (
  /** @type {import('plop').NodePlopAPI} */
  plop
) {
  plop.setHelper('dashedName', (txt) => txt.toLowerCase().replace(/ /g, "-"));
  plop.setHelper('dateTemp', () => format(new Date(), 'yyyy-MM-dd'));
 
  // create your generators here
  plop.setGenerator('template', {
    description: 'This is content template generator plop',
    prompts,
    actions
  });
};
  1. Create handlebar file .hbs as the reference template to generate your format. For for how to use handlebars file you can follow guide
blog.template.hbs
---
title:
description:
date: {{ dateTemp }}
published: {{ dateTemp }}
isPublished: false
pageType: public
tags:
  - blog
image: /
 
---
 
## title
 
paragraph

If you notice here I have some variables that I use are called plop helpers.
In the plopfile create plop.setHelper function and pass key & callback

  // date-fns package is used to format date values
  plop.setHelper('dashedName', (txt) => txt.toLowerCase().replace(/ /g, "-"));
  plop.setHelper('dateTemp', () => format(new Date(), 'yyyy-MM-dd'));
  1. Run plop from terminal
package.json
{
    ...,
    "scripts": {
        "plop": "plop"
    },
    ...
}
 

there after with your preferred package manger

yarn run plop

You can also run plop [generatorName] to trigger a generator directly.

Conclusion

Plop.js is a powerful tool for automating the generation of code and text files in a consistent manner, especially in projects where maintaining structure and format is essential.
By setting up custom templates and leveraging Plop's helper functions, you can streamline repetitive tasks, ensuring that every new file adheres to your project's standards. This not only saves time but also reduces errors.

Although AI tools are growing in popularity, Plop.js remains a valuable, deterministic approach to generating code snippets, providing flexibility and control over your project's structure.