How to get VuePress latest pages from outside

Category:
Tags:
Last Updated: 2021/12/13 12:40:54

On Ninja Press, latest articles are requested from Web Ninja (opens new window), however, VuePress itself doesn't have any functions for getting pages from outside. In this site, files for getting latest posts are created when executing yarn build.

# enchantApp.js

When you create a new VuePress project, enchantApp.js is automatically created.

Official Reference (opens new window) provides very simple explanation, but actually this file is very useful because in this file a variable siteData shows a lot of information then you can try various things.

# Code

Fanally, enchantApp.js is like this:


const fs = require('fs')
const path = require('path')
const moment = require('moment');
const _ = require("lodash");

let _done =false;

export default ({
  Vue, // the version of Vue being used in the VuePress app
  options, // the options for the root Vue instance
  router, // the router instance for the app
  siteData // site metadata
}) => {
	// skipped on `yarn dev` because `global` cannot be referred then.
	try {
		global;
	} catch(e) {
		return;
	}

	// this exported function itself is called many times in one build action.
	// you should ignore more than 2 times.
	if (_done) return;
	_done = true;
	
	let pages = siteData.pages.filter(post => {
		if (post.relativePath) {
			// just under /articles/ 
			if (post.relativePath.indexOf("articles/") !== 0) {
				return false;
			}

			// ignore README.md
			if (post.relativePath.substr(-9) === "README.md") {
				return false;
			}
		}

		return true;
	}).map(post => {
		const url = "https://web-ninja21.com" + path.join("/press/" ,post.regularPath);

		return {
			title: post.title, 
			url, 
			category: post.frontmatter.category, 
			tags: post.frontmatter.tags, 
			date: moment(post.frontmatter.date).format("YYYY/MM/DD hh:mm"),

			// moment gives warnings because lastUpdated format is different. But actually you can build files.
			// lastUpdated: moment(post.lastUpdated).format("YYYY/MM/DD hh:mm"),
		};
	});
	pages = _.orderBy(pages, ["date"], ["desc"]);

	// JSON file
	// `__dirname` doesn't work well , the path from the place `yarn build` will be executed.
	fs.writeFileSync(
		path.resolve('./src/.vuepress/dist/latest.json'),
		JSON.stringify(pages)
	);

	// like JSONP
	fs.writeFileSync(
		path.resolve('./src/.vuepress/dist/latest.js'),
		`window && window._ninjaPress && window._ninjaPress(${JSON.stringify(pages)})`
	);
	
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

Then latest.json and latest.js would be created in dist directory.

Category:
Tags:
Last Updated: 2021/12/13 12:40:54
Copyright © Web Ninja All Rights Reserved.