-
Notifications
You must be signed in to change notification settings - Fork 2
/
compile.js
88 lines (68 loc) · 2.09 KB
/
compile.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const pug = require('pug')
const path = require('path')
const mkdirp = require('mkdirp')
const fs = require('fs')
const marked = require('marked')
const glob = require('glob')
const ncp = require('ncp').ncp
const isProduction = process.env.NODE_ENV === 'production'
const templatesPath = path.join(__dirname, 'app', 'templates')
const publicPath = path.join(__dirname, 'public')
const pugOptions = {
basedir: path.join(__dirname, 'app'),
pretty: !isProduction
}
/*
* Compile static pages
* TODO: move to brunch
*/
const staticPages = {
'main.pug': 'index.html'
}
for (const page in staticPages) {
const filename = path.join(templatesPath, page)
const html = pug.renderFile(filename, pugOptions)
const outputFile = path.join(publicPath, staticPages[page])
mkdirp(path.dirname(outputFile), () => {
fs.writeFile(outputFile, html)
console.log(`-> ${outputFile}`)
})
}
/*
* Compiles a post within a given dir
*/
const compilePost = (postPath, onDone) => {
const postConfig = require(path.join(postPath, 'post.json'))
fs.readFile(path.join(postPath, 'post.md'), (err, data) => {
if (err) return
const postMarkdown = data.toString()
const postContent = marked(postMarkdown)
const outputDir = path.join(publicPath, postConfig.output || postPath)
mkdirp(outputDir, () => {
const template = path.join(templatesPath, 'post.pug')
const html = pug.renderFile(template, Object.assign({}, pugOptions, {
page: {
title: postConfig.title
},
post: Object.assign({
content: postContent
}, postConfig)
}))
const outputFile = path.join(outputDir, 'index.html')
fs.writeFile(outputFile, html, () => {
const assetsPath = path.join(postPath, 'assets')
ncp(assetsPath, publicPath)
console.log(`Assets ${assetsPath} linked`)
onDone && onDone(null)
})
console.log(`-> ${outputFile}`)
})
})
}
/*
* Compile all posts in /posts dir
*/
glob(path.join(__dirname, 'posts', '*/'), (err, files) => {
if (err) return
files.forEach((file) => compilePost(file))
})