-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuild.js
80 lines (71 loc) · 2.59 KB
/
build.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
const { promisify } = require('util')
const { exec } = require('child_process')
const { readFile, writeFile } = require('fs')
const fetch = require('node-fetch')
const { parseTsv } = require('libe-utils')
const execPromise = promisify(exec)
const cheerio = require('cheerio')
const config = require('./src/config')
async function readFilePromise (path, encoding = 'utf8') {
const result = await new Promise((resolve, reject) => {
readFile(path, encoding, (err, data) => {
if (err) resolve({ success: null, error: err })
else resolve({ success: data, error: null })
})
})
return result
}
async function writeFilePromise (path, data, encoding = 'utf8') {
const result = await new Promise((resolve, reject) => {
writeFile(path, data, encoding, err => {
if (err) resolve({ success: null, error: err })
else resolve({ success: true, error: null })
})
})
return result
}
async function fetchSheet (spreadsheet) {
const reach = await fetch(spreadsheet)
if (!reach.ok) throw reach
const data = await reach.text()
const meta = parseTsv(data, [5, 5])[1][0]
console.log(meta)
return meta
}
async function build () {
// Build app
const { stdout, stderr } = await execPromise('react-scripts build')
if (stderr) throw Error(stderr)
console.log(stdout)
// Read build index.html
console.log('Reading file at ./build/index.html')
const { success: fileData, error: readError } = await readFilePromise('./build/index.html')
if (readError) throw readError
// Add meta tags
console.log('\nAdding meta tags')
const { title, url, description, author, image } = config.meta
const $ = cheerio.load(fileData)
$('head').append(`
<title>Libération.fr – ${title}</title>
<link rel="canonical" href="${url}" />
<meta name="author" content="${author}" />
<meta name="description" content="${description}" />
<meta property="og:url" content="${url}" />
<meta property="og:title" content="${title}" />
<meta property="og:description" content="${description}" />
<meta property="og:image" content="${image}" />
<meta name="twitter:url" content="${url}" />
<meta name="twitter:title" content="${title}" />
<meta name="twitter:description" content="${description}" />
<meta name="twitter:image" content="${image}" />
`)
// Save index.html
console.log('\nSaving file at ./build/index.html')
const { success, error: writeError } = await writeFilePromise('./build/index.html', $.html())
if (writeError) throw writeError
// Return
console.log('\nDone.')
}
build()
.then(res => process.exit(0))
.catch(err => process.exit(1))