-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
index.js
306 lines (263 loc) Β· 7.3 KB
/
index.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
'use strict'
/**
* Module dependencies.
*/
const EventEmitter = require('events').EventEmitter
const WebpackDevServer = require('webpack-dev-server')
const { frontmatterEmitter } = require('@vuepress/markdown-loader')
const webpack = require('webpack')
const chokidar = require('chokidar')
const { path, fs, logger } = require('@vuepress/shared-utils')
const HeadPlugin = require('../webpack/HeadPlugin')
const DevLogPlugin = require('../webpack/DevLogPlugin')
const createClientConfig = require('../webpack/createClientConfig')
const { applyUserWebpackConfig } = require('../util/index')
module.exports = class DevProcess extends EventEmitter {
constructor (context) {
super()
this.context = context
}
/**
* Prepare essential data for launch dev server.
*/
async process () {
this.context.resolveCacheLoaderOptions()
this.watchSourceFiles()
this.watchUserConfig()
this.watchFrontmatter()
this.setupDebugTip()
await this.resolvePort()
await this.resolveHost()
this.prepareWebpackConfig()
return this
}
/**
* Hande file's update, need to re-prepare app context.
*
* @param {string} type
* @param {string} target
*/
handleUpdate (type, target) {
logger.debug(type, target)
if (!path.isAbsolute(target)) {
target = path.join(this.context.sourceDir, target)
}
if (target.endsWith('.js')) {
// Bust cache.
delete require.cache[target]
}
this.emit('fileChanged', {
type,
target
})
}
/**
* Watch user's source document files.
*/
watchSourceFiles () {
// watch add/remove of files
this.pagesWatcher = chokidar.watch([
'**/*.md',
'.vuepress/components/**/*.vue'
], {
cwd: this.context.sourceDir,
ignored: ['.vuepress/**/*.md', 'node_modules'],
ignoreInitial: true
})
this.pagesWatcher.on('add', target => this.handleUpdate('add', target))
this.pagesWatcher.on('unlink', target => this.handleUpdate('unlink', target))
}
/**
* Watch user's config files and extra files.
*/
watchUserConfig () {
this.watchFiles = [
'.vuepress/config.js',
'.vuepress/config.yml',
'.vuepress/config.toml'
].concat(
(
this.context.siteConfig.extraWatchFiles || []
).map(file => normalizeWatchFilePath(file, this.context.sourceDir))
)
logger.debug('watchFiles', this.watchFiles)
this.configWatcher = chokidar.watch(this.watchFiles, {
cwd: this.context.sourceDir,
ignoreInitial: true
})
this.configWatcher.on('change', target => this.handleUpdate('change', target))
}
/**
* Also listen for frontmatter changes from markdown files
*/
watchFrontmatter () {
frontmatterEmitter.on('update', target => this.handleUpdate('frontmatter', target))
}
/**
* Resolve used port
*/
async resolvePort () {
this.port = await resolvePort(this.context.options.port || this.context.siteConfig.port)
}
/**
* Resolve used host
*/
async resolveHost () {
const { host, displayHost } = await resolveHost(this.context.options.host || this.context.siteConfig.host)
this.host = host
this.displayHost = displayHost
}
/**
* Set up a shortcut to debug context under dev.
*/
setupDebugTip () {
// debug in a running dev process.
process.stdin
&& process.stdin.on('data', chunk => {
const parsed = chunk.toString('utf-8').trim()
if (parsed === '*') {
console.log(Object.keys(this.context))
}
if (this.context[parsed]) {
console.log(this.context[parsed])
}
})
}
/**
* Prepare webpack for dev process.
*/
prepareWebpackConfig () {
// resolve webpack config
let config = createClientConfig(this.context)
config
.plugin('html')
// using a fork of html-webpack-plugin to avoid it requiring webpack
// internals from an incompatible version.
.use(require('vuepress-html-webpack-plugin'), [{
template: this.context.devTemplate
}])
config
.plugin('site-data')
.use(HeadPlugin, [{
tags: this.context.siteConfig.head || []
}])
config
.plugin('vuepress-log')
.use(DevLogPlugin, [{
port: this.port,
displayHost: this.displayHost,
publicPath: this.context.base,
clearScreen: !(this.context.options.debug || !this.context.options.clearScreen)
}])
config = config.toConfig()
const userConfig = this.context.siteConfig.configureWebpack
if (userConfig) {
config = applyUserWebpackConfig(userConfig, config, false /* isServer */)
}
this.webpackConfig = config
}
/**
* Create dev server
* @returns {module.DevProcess}
*/
createServer () {
const contentBase = path.resolve(this.context.sourceDir, '.vuepress/public')
const serverConfig = Object.assign({
disableHostCheck: true,
compress: true,
clientLogLevel: 'error',
hot: true,
quiet: true,
headers: {
'access-control-allow-origin': '*'
},
open: this.context.options.open,
publicPath: this.context.base,
watchOptions: {
ignored: [
/node_modules/,
`!${this.context.tempPath}/**`
]
},
historyApiFallback: {
disableDotRule: true,
rewrites: [
{ from: /./, to: path.posix.join(this.context.base, 'index.html') }
]
},
overlay: false,
host: this.host,
contentBase,
before: (app, server) => {
if (fs.existsSync(contentBase)) {
app.use(this.context.base, require('express').static(contentBase))
}
this.context.pluginAPI.applySyncOption('beforeDevServer', app, server)
},
after: (app, server) => {
this.context.pluginAPI.applySyncOption('afterDevServer', app, server)
}
}, this.context.siteConfig.devServer || {})
WebpackDevServer.addDevServerEntrypoints(this.webpackConfig, serverConfig)
const compiler = webpack(this.webpackConfig)
this.server = new WebpackDevServer(compiler, serverConfig)
return this
}
/**
* delegate listen call.
*
* @param callback handler when connection is ready.
* @returns {module.DevProcess}
*/
listen (callback) {
this.server.listen(this.port, this.host, (err) => {
if (typeof callback === 'function') {
callback(err)
}
})
return this
}
}
/**
* Resolve host.
*
* @param {string} host user's host
* @returns {{displayHost: string, host: string}}
*/
function resolveHost (host) {
const defaultHost = '0.0.0.0'
host = host || defaultHost
const displayHost = host === defaultHost
? 'localhost'
: host
return {
displayHost,
host
}
}
/**
* Resolve port.
*
* @param {number} port user's port
* @returns {Promise<number>}
*/
async function resolvePort (port) {
const portfinder = require('portfinder')
portfinder.basePort = parseInt(port) || 8080
port = await portfinder.getPortPromise()
return port
}
/**
* Normalize file path and always return relative path,
*
* @param {string} filepath user's path
* @param {string} baseDir source directory
* @returns {string}
*/
function normalizeWatchFilePath (filepath, baseDir) {
const { isAbsolute, relative } = require('path')
if (isAbsolute(filepath)) {
return relative(baseDir, filepath)
}
return filepath
}