It’s been nearly 6 years since my last post about static site generators, and I still don’t understand why there’s a whole host of them. In my experience, static site generators like Hugo solve a trivial problem badly, and leave you to clean up the mess. Thankfully, the Node.js ecosystem makes building a blog as a static site easy: just choose your HTML templating language, pull in marked to convert your blog posts from markdown to HTML, write a for loop to loop over all your posts, and you’re done.

Picking a templating language for building your layout comes with a lot of tradeoffs, and I’ve used many different ones. This blog’s layout is written in pug. Mastering JS’ layout is written using ES6 template strings. Both Pug and template literals have their advantages, but they share one key disadvantage: the layout itself isn’t plain HTML, which means you need tooling to get a preview of what your layout looks like. On the other hand, Vue supports plain HTML templates, which is why I’m building future blogs on Vue, and likely switching my existing blogs to Vue as well.

Setup

The general idea of compiling a blog is taking an array of blog posts, compiling the corresponding markdown into HTML, plugging it into an HTML layout, and creating a list view of the compiled blog posts. For example, say you have a my-first-blog-post.md file:

This is my **first** blog post!

Here’s an index.js file that you may use to compile this Markdown file into an index.html that lists blog posts and a my-first-blog-post.html file that contains the body of the blog post.

const fs = require('fs');
const marked = require('marked');

const posts = [
  {
    title: 'My First Blog Post',
    source: './my-first-blog-post.md',
    dest: './my-first-blog-post.html'
  }
];

for (const post of posts) {
  let content = fs.readFileSync(post.source, 'utf8');
  content = marked(content);
  fs.writeFileSync(post.dest, content);
  console.log('Wrote', post.dest);
}

fs.writeFileSync('./index.html', `
  <h1>Blog Posts</h1>
  ${posts.map(blogPostLink).join('\n')}
`);

function blogPostLink(post) {
  return `<div><a href="${post.dest}">${post.title}</a></div>`;
}

Yes, I’m not using front matter. Front matter is neat, especially if you have non-technical people contributing content, but I don’t, so front matter isn’t useful in this case.

Running the above script produces the below my-first-blog-post.html file:

<p>This is my <strong>first</strong> blog post!</p>

And the below index.html file:

  <h1>Blog Posts</h1>
  <div><a href="./my-first-blog-post.html">My First Blog Post</a></div>

Commit this code to GitHub, hook up Netlify, and you get a functioning proof of concept for a blog.

#vue #node #javascript #web-development #developer

Using Vue as a Node.js Static Site Generator
2.80 GEEK