In my journey to be a more productive developer, I am always looking for ways to overcome barriers to productivity. One of the biggest barriers I have found is the time it takes to create a new blog post. I have tried a few different approaches, but I have found that the best way to create a new blog post is to use a template. This allows me to focus on the content of the post, rather than the formatting, copying and pasting that it usually takes to make a new blog post.
I’m currently using Astro for my blog, and it has been refreshing moving back to using pure markdown files for my blog posts. I have found that I am able to focus more on the content of my posts, rather than worrying about the whole deployment process.
Back when I first started with Gatsby I used a little node package I found that would generate me a new blog post template. I’ve moved on a bit since then, preferring to roll my own little scripts when and where I can, and here’s an example of one.
The Script
Add a file called new-post.js
to your root directory with the following contents:
const fs = require("fs");
const slugify = require("slugify");
const dayjs = require("dayjs");
const now = dayjs().toISOString();
const title = process.argv[2];
if (!title) {
console.error("Please provide a title for the post.");
process.exit(1);
}
const slug = slugify(title, {
lower: true,
strict: true,
locale: "en",
});
const filename = `${now.slice(0, 10)}-${slug}.md`;
const content = `---
title: ${title}
author: YOUR NAME HERE
pubDatetime: ${now}
featured: false
draft: true
tags:
- tag
ogImage: ""
description: ""
---
WRITE_YOUR_POST_HERE
`;
const filepath = `src/content/blog/${filename}`;
fs.writeFileSync(filepath, content);
console.log(`Created file: ${filepath}`);
Then, update your yarn scripts in package.json
to include the following:
"new-post": "node new-post.js"
You’ll need to install a few dependencies as well:
yarn add slugify dayjs
After that, simply run yarn new-post "My New Post"
and you’ll have a new markdown file in your src/content/blog
directory with the correct frontmatter and a slugified filename.
Easy peasy.