Use MomentJS with VuePress.
A static site is made up of HTML files, CSS files, and JavaScript (JS) files. A static site generator uses raw data (like markdown files) and templates to generate HTML, CSS, and JS files.
What is VuePress?
VuePress is a static site generator that is optimized for creating technical documents using markdown files. It renders a single page app that is powered by Vue, Vue Router, and Webpack. You can even use Vue within your markdown files!
What is MomentJS?
The MomentJS library is a free ($0), and free (open source), JavaScript wrapper for the Date object (similar in concept to jQuery being a wrapper for the JavaScript language). This library is used to validate, parse, and manipulate dates on the client-side.
Why this Post Exists.
I am new to VuePress. My previous static site generator was Jekyll (as a result of pushing technical documents to GitHub Pages). I switched to VuePress as a direct result of using Vue in my current projects. It's natural to document my Vue adventures with VuePress, yes?
Now I'm thinking: "Gee, that date format looks like crap!! How do I fix it?" My favourite search engine let me down completely ("No shortcuts today, you'll have to figure it out. Beep.") Oh well, here I go...
Format VuePress Dates with MomentJS.
The first step is to add the MomentJS package to my current VuePress installation.
- From a terminal, run the following command in the root directory of the VuePress project to download and install the MomentJS component:
$ npm install moment --save
NOTE: The
--save
flag adds an entry to the package.json file.
MomentJS is now ready to use in a VuePress component.
- Create a component called
/docs/.vuepress/components/Date.vue
and add the following:
<template>
<span>{{ formatDate($frontmatter.date) }}</span>
</template>
<script>
import moment from 'moment'
export default {
methods: {
formatDate(date, format = 'dddd Do MMMM YYYY') {
moment.locale('en-NZ')
return (
moment(date).format(format) +
', ' +
moment(date)
.startOf()
.fromNow() +
'.'
)
}
}
}
</script>
- Create a
/docs/test.md
markdown file to test the component:
---
date: 2020-01-15
---
Date: <Date />
NOTE: I set the locale to 'en-NZ' in
Date.vue
, so the date element in the front matter above follows the YYYY-MM-DD convention.
- From a terminal, run the following command to start the server:
$ vuepress dev docs
- Finally, open a browser and visit http://localhost:8080/test.html🡕.
I can now drop a <Date />
component on any page that uses a date element in it's front matter.
NOTE: The BlogIndex.vue component uses a slightly modified version of the
Date.vue
code listed above.
Summary.
VuePress (specifically) and Vue (generally) are flexible, adaptable, and performant. It's characteristics like these that make using Vue-based technologies such a joy.