-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
build.js
181 lines (155 loc) Β· 5.73 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
module.exports = async function build (sourceDir, cliOptions = {}) {
process.env.NODE_ENV = 'production'
const fs = require('fs-extra')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const readline = require('readline')
const escape = require('escape-html')
const prepare = require('./prepare')
const createClientConfig = require('./webpack/createClientConfig')
const createServerConfig = require('./webpack/createServerConfig')
const { createBundleRenderer } = require('vue-server-renderer')
const { normalizeHeadTag, applyUserWebpackConfig } = require('./util')
process.stdout.write('Extracting site metadata...')
const options = await prepare(sourceDir)
if (cliOptions.outDir) {
options.outDir = cliOptions.outDir
}
const { outDir } = options
await fs.remove(outDir)
let clientConfig = createClientConfig(options, cliOptions).toConfig()
let serverConfig = createServerConfig(options, cliOptions).toConfig()
// apply user config...
const userConfig = options.siteConfig.configureWebpack
if (userConfig) {
clientConfig = applyUserWebpackConfig(userConfig, clientConfig, false)
serverConfig = applyUserWebpackConfig(userConfig, serverConfig, true)
}
// compile!
const stats = await compile([clientConfig, serverConfig])
const serverBundle = require(path.resolve(outDir, 'manifest/server.json'))
const clientManifest = require(path.resolve(outDir, 'manifest/client.json'))
// remove manifests after loading them.
await fs.remove(path.resolve(outDir, 'manifest'))
// find and remove empty style chunk caused by
// https://github.com/webpack-contrib/mini-css-extract-plugin/issues/85
// TODO remove when it's fixed
await workaroundEmptyStyleChunk()
// create server renderer using built manifests
const renderer = createBundleRenderer(serverBundle, {
clientManifest,
runInNewContext: false,
inject: false,
template: await fs.readFile(path.resolve(__dirname, 'app/index.ssr.html'), 'utf-8')
})
// pre-render head tags from user config
const userHeadTags = (options.siteConfig.head || [])
.map(renderHeadTag)
.join('\n ')
// render pages
console.log('Rendering static HTML...')
for (const page of options.siteData.pages) {
await renderPage(page)
}
// if the user does not have a custom 404.md, generate the theme's default
if (!options.siteData.pages.some(p => p.path === '/404.html')) {
await renderPage({ path: '/404.html' })
}
readline.clearLine(process.stdout, 0)
readline.cursorTo(process.stdout, 0)
if (options.siteConfig.serviceWorker) {
console.log('Generating service worker...')
const wbb = require('workbox-build')
wbb.generateSW({
swDest: path.resolve(outDir, 'service-worker.js'),
globDirectory: outDir,
globPatterns: ['**\/*.{js,css,html,png,jpg,jpeg,gif,svg,woff,woff2,eot,ttf,otf}']
})
}
// DONE.
const relativeDir = path.relative(process.cwd(), outDir)
console.log(`\n${chalk.green('Success!')} Generated static files in ${chalk.cyan(relativeDir)}.`)
// --- helpers ---
function compile (config) {
return new Promise((resolve, reject) => {
webpack(config, (err, stats) => {
if (err) {
return reject(err)
}
if (stats.hasErrors()) {
stats.toJson().errors.forEach(err => {
console.error(err)
})
reject(new Error(`Failed to compile with errors.`))
return
}
resolve(stats.toJson({ modules: false }))
})
})
}
function renderHeadTag (tag) {
const { tagName, attributes, innerHTML, closeTag } = normalizeHeadTag(tag)
return `<${tagName}${renderAttrs(attributes)}>${innerHTML}${closeTag ? `</${tagName}>` : ``}`
}
function renderAttrs (attrs = {}) {
const keys = Object.keys(attrs)
if (keys.length) {
return ' ' + keys.map(name => `${name}="${escape(attrs[name])}"`).join(' ')
} else {
return ''
}
}
async function renderPage (page) {
const pagePath = page.path
readline.clearLine(process.stdout, 0)
readline.cursorTo(process.stdout, 0)
process.stdout.write(`Rendering page: ${pagePath}`)
const pageMeta = renderPageMeta(page.frontmatter && page.frontmatter.meta)
const context = {
url: pagePath,
userHeadTags,
pageMeta,
title: 'VuePress',
lang: 'en'
}
let html
try {
html = await renderer.renderToString(context)
} catch (e) {
console.error(chalk.red(`Error rendering ${pagePath}:`))
throw e
}
const filename = pagePath.replace(/\/$/, '/index.html').replace(/^\//, '')
const filePath = path.resolve(outDir, filename)
await fs.ensureDir(path.dirname(filePath))
await fs.writeFile(filePath, html)
}
function renderPageMeta (meta) {
if (!meta) return ''
return meta.map(m => {
let res = `<meta`
Object.keys(m).forEach(key => {
res += ` ${key}="${escape(m[key])}"`
})
return res + `>`
}).join('')
}
async function workaroundEmptyStyleChunk () {
const styleChunk = stats.children[0].assets.find(a => {
return /styles\.\w{8}\.js$/.test(a.name)
})
if (!styleChunk) return
const styleChunkPath = path.resolve(outDir, styleChunk.name)
const styleChunkContent = await fs.readFile(styleChunkPath, 'utf-8')
await fs.remove(styleChunkPath)
// prepend it to app.js.
// this is necessary for the webpack runtime to work properly.
const appChunk = stats.children[0].assets.find(a => {
return /app\.\w{8}\.js$/.test(a.name)
})
const appChunkPath = path.resolve(outDir, appChunk.name)
const appChunkContent = await fs.readFile(appChunkPath, 'utf-8')
await fs.writeFile(appChunkPath, styleChunkContent + appChunkContent)
}
}