🇬🇧 Add JSON Feed support to VuePress pages thanks to 🦊 GitLab Runners

2018-07-05

This is a quick article. I need to add JSON Feed support to my VuePress website. I use YAML headers in my markdown blog post:

---
title: 🇬🇧 Add JSON Feed support to VuePress pages thanks to 🦊 GitLab Runners
lang: us-EN
date: "2018-07-05"
month: "2018-07"
classification: "JavaScript - VuePress - GitLab Runners"
teaser: ""
---

So, I will use yaml-front-matter to help me to build a JSON feed file.

First: Set up

Install yaml-front-matter in your VuePress project:

npm install yaml-front-matter -save

Second: Create a script to generate the JSON Feed file

At the root of your project, create a gen-json-feed.js file with this content:

const fs = require('fs')
const yamlFront = require('yaml-front-matter')
const path = require('path')

const docFolder = './docs/articles/'
const homepage = 'https://k33g.gitlab.io'

let feed = {
  version: 'https://jsonfeed.org/version/1',
  user_comment: 'Json Feed from k33g.gitlab.io',
  title: 'k33g.gitlab.io - JSON Feed',
  description: 'Geek Blog Posts by @k33g_org',
  home_page_url: homepage,
  feed_url: `${homepage}/feed.json`,
  author: {
    name: '@k33G_org',
    url: 'https://twitter.com/k33g_org?lang=en'
  },
  items: []
}

fs.readdirSync(docFolder).forEach(file => {

  console.log(`${homepage}/articles/${path.parse(file).name}.html`)
  let contents = fs.readFileSync(`${docFolder}${file}`, 'utf8')
  let yaml = yamlFront.loadFront(contents)

  feed.items.push({
    title: yaml.title,
    date_published: yaml.date,
    id: `${homepage}/articles/${path.parse(file).name}.html`,
    url: `${homepage}/articles/${path.parse(file).name}.html`,
    content_html: yaml.classification + (yaml.teaser!=="" ? ` | ${yaml.teaser}` : "") // __content:
  })

})
feed.items.reverse()
fs.writeFileSync('./public/feed.json', JSON.stringify(feed,null,2));

Remarks:

  • my blog posts are in ./docs/articles/
  • I generate the file at the root of the ./public directory

So, adapt the script for your own website.

Third: Update .gitlab-ci.yml to add a job to generate the fedd file

Update your .gitlab-ci.yml like that:

{
  "main": "index.js",
  "directories": {
    "doc": "docs"
  },
  "scripts": {
    "docs:build": "vuepress build docs;",
    "json:feed": "node gen-json-feed.js"
  },
  "dependencies": {
    "vuepress": "^0.10.0",
    "yaml-front-matter": "^4.0.0"
  }
}

Remark: I only add this line: "json:feed": "node gen-json-feed.js"

Then:

  • Update your GitLab project: git add ., git commit -m "✨ Json Feed", git push
  • Wait for the build pipeline
  • ... And now, you can get your feed here: https://k33g.gitlab.io/feed.json

Simple 😉

Last Articles

Last Updated: 7/14/2018, 8:20:11 AM