-
Notifications
You must be signed in to change notification settings - Fork 29
/
build.js
89 lines (77 loc) Β· 2.69 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
81
82
83
84
85
86
87
88
89
const fs = require('fs-extra')
const path = require('path')
const webpack = require('webpack')
const handlebars = require('handlebars')
const chalk = require('picocolors')
const wpConf = require('./webpack.config')
const printConfig = require('./printConfig')
const { recomputeAssets } = require('./options')
module.exports = async function build (options, log) {
log.info('Building for production...')
if (options.printConfig) {
if (options.target.modern) {
await printConfig({ options, modern: true, log })
}
if (options.target.legacy) {
await printConfig({ options, modern: false, log })
}
return
}
const webpackConfig = await wpConf(options)
const modernCompiler = webpack(webpackConfig.modern)
const legacyCompiler = webpack(webpackConfig.legacy)
const target = path.join(options.dir, options.dist)
if (await fs.pathExists(target)) {
await fs.remove(target)
log.info('Deleted existing', chalk.gray(options.dist), 'directory')
}
if (options.target.modern) {
log.info('Building modern bundle')
await run(modernCompiler, { modern: true })
}
if (options.target.legacy) {
log.info('Building legacy bundle')
await run(legacyCompiler, { modern: false })
}
async function run (compiler, { modern }) {
if (!options.quiet) {
require('./reporter')(compiler, log, { printAssets: true, dir: options.dir })
}
try {
await new Promise((resolve, reject) => {
compiler.run(async function (err, stats) {
try {
if (err) {
throw err
}
if (stats.hasErrors()) {
throw new Error('Compilation failed')
}
// we've compiled assets, we therefore need to recompute options.assets
options = recomputeAssets(options, { modern })
if (options.static && isDir(path.join(options.dir, options.static))) {
await fs.copy(path.join(options.dir, options.static), path.join(options.dir, options.dist, 'assets'))
}
const head = options.head && handlebars.compile(options.head)(options)
const body = options.body && handlebars.compile(options.body)(options)
const html = options.html && handlebars.compile(options.html)(Object.assign({}, options, { head, body }))
html && await fs.writeFile(path.join(target, modern ? 'index.html' : 'index.legacy.html'), html)
resolve()
} catch (err) {
reject(err)
}
})
})
} catch (err) {
log.error(chalk.red(err))
process.exit(1)
}
}
}
function isDir (path) {
try {
return fs.lstatSync(path).isDirectory(path)
} catch (err) {
return false
}
}