-
Notifications
You must be signed in to change notification settings - Fork 411
/
buildCommand.js
94 lines (84 loc) · 2.76 KB
/
buildCommand.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
90
91
92
93
94
import fsp from 'fs-promise'
import path from 'path'
import thenify from 'thenify'
import filesize from 'filesize'
import getConfig from '../../util/getConfig'
import sortModulesBySize from '../../stats/sortModulesBySize'
import {
getWebpackCompiler,
getDocumentElement,
ReactDOM
} from '@sanity/server'
export default {
name: 'build',
command: 'build [outputDir]',
describe: 'Builds the current Sanity configuration to a static bundle',
handler: ({output, options}) => {
const outputDir = options._[1] || path.join(options.rootDir, 'dist')
const config = getConfig(options.rootDir).get('server')
const compilationConfig = {
env: 'production',
staticPath: resolveStaticPath(options.rootDir, config),
basePath: options.rootDir,
outputPath: path.join(outputDir, 'static')
}
const compiler = getWebpackCompiler(compilationConfig)
const compile = thenify(compiler.run.bind(compiler))
const spin = output.spinner('Building Sanity...')
spin.start()
const bundle = {}
return compile()
.then(statistics => {
const stats = statistics.toJson()
if (stats.errors && stats.errors.length > 0) {
throw new Error(
`Errors while building:\n\n${stats.errors.join('\n\n')}`
)
}
const chunkMap = {}
stats.chunks.forEach(chunk =>
chunk.files.forEach(file => {
chunkMap[file] = chunk.hash
})
)
bundle.stats = stats
return chunkMap
})
.then(chunkMap => {
spin.text = 'Building index document'
return getDocumentElement(compilationConfig, {
scripts: ['https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en', 'vendor.bundle.js', 'app.bundle.js'].map(asset => ({
path: `js/${asset}`,
hash: chunkMap[asset]
}))
})
})
.then(doc =>
fsp.writeFile(
path.join(outputDir, 'index.html'),
`<!doctype html>${ReactDOM.renderToStaticMarkup(doc)}`
)
)
.then(() => spin.stop())
.then(() => {
bundle.stats.warnings.forEach(output.print)
output.print(`Javascript bundles built, time spent: ${bundle.stats.time}ms`)
if (options.stats) {
output.print('\nLargest modules (unminified, uncompressed sizes):')
sortModulesBySize(bundle.stats.modules).slice(0, 10).forEach(module =>
output.print(`[${filesize(module.size)}] ${module.name}`)
)
}
})
.catch(err => {
spin.stop()
output.error(err)
})
}
}
function resolveStaticPath(rootDir, config) {
const {staticPath} = config
return path.isAbsolute(staticPath)
? staticPath
: path.resolve(path.join(rootDir, staticPath))
}