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?
- Add plop yo your project
- Create a
plopfile
in the root directory of the project
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
.
- Create your first plop file.
A plopfile as a node module that exports a function which accepts the plop
object as its first parameter.
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
- Create handlebar file
.hbs
as the reference template to generate your format. For for how to use handlebars file you can follow guide
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
- Run plop from terminal
there after with your preferred package manger
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.