-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviews.js
More file actions
executable file
·72 lines (63 loc) · 1.81 KB
/
views.js
File metadata and controls
executable file
·72 lines (63 loc) · 1.81 KB
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
#! /usr/bin/env node
const fs = require('fs')
const path = require('path')
const util = require('util')
const register = require('babel-register')
const clearModule = require('clear-module')
const mkdirp = require('mkdirp')
const rimraf = require('rimraf')
const chokidar = require('chokidar')
const ReactDOMServer = require('react-dom/server')
register({
presets: ["es2015", "react"],
extensions: [".jsx"],
})
let watchMode = false
process.argv.slice(2).forEach(flag => {
switch (flag) {
case '--watch': return watchMode = true
default: throw new Error(`Unrecognized flag "${flag}"`)
}
})
const readdir = util.promisify(fs.readdir.bind(fs))
const writeFile = util.promisify(fs.writeFile.bind(fs))
const rm = util.promisify(rimraf)
function writeView(file) {
const moduleName = `./views/${file.base}`
console.log(`Compiling ${moduleName}`)
clearModule(moduleName)
const component = require(moduleName)
const html = ReactDOMServer.renderToStaticMarkup(component())
return writeFile(path.join(__dirname, 'html', `${file.name}.html`), html, { encoding: 'utf8' })
}
async function compileViews() {
const files = await readdir(path.join(__dirname, '/views'))
const jsxFiles = files.map(file => path.parse(file)).filter(file => file.ext === '.jsx')
return Promise.all(jsxFiles.map(file => {
if (watchMode) {
try {
writeView(file)
} catch (err) {
console.error(err)
}
} else {
writeView(file)
}
}))
}
async function main() {
await mkdirp('html')
await compileViews()
console.log('Compiled .jsx files in /views to /html')
if (watchMode) watch()
}
function watch() {
chokidar.watch('./views', { ignoreInitial: true }).on('all', async () => {
await rm('html')
await main()
})
}
process.on("unhandledRejection", (reason) => {
throw reason
})
main()