-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathhmr.js
More file actions
76 lines (65 loc) · 2.51 KB
/
hmr.js
File metadata and controls
76 lines (65 loc) · 2.51 KB
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
/* eslint-disable nullstack/no-undef */
import { existsSync, open, writeFileSync } from 'fs'
import path from 'path'
import logger from '../builders/logger'
function waitCompiler(next) {
open(path.join(__dirname, '.compiling'), (error, exists) => {
if (!exists) {
next()
} else {
setTimeout(() => {
waitCompiler(next)
}, 100)
}
})
}
export default function hmr(server) {
const progress = logger('client', 'development')
if (module.hot) {
const customConfig = path.resolve(process.cwd(), 'webpack.config.js')
const webpackConfigs = existsSync(customConfig)
? __non_webpack_require__(customConfig)
: __non_webpack_require__(path.join(__dirname, '..', 'node_modules', 'nullstack', 'webpack.config.js'))
function resolve(pkg) {
if (process.cwd().endsWith('/nullstack/tests') || process.cwd().endsWith('\\nullstack\\tests')) {
return path.join(__dirname, '..', '..', 'node_modules', pkg)
}
return pkg
}
const webpack = __non_webpack_require__(resolve(`webpack`))
const webpackDevMiddleware = __non_webpack_require__(resolve(`webpack-dev-middleware`))
const disk = process.env.NULLSTACK_ENVIRONMENT_DISK === 'true'
const trace = process.env.__NULLSTACK_TRACE === 'true'
const webpackConfig = webpackConfigs[1](null, {
environment: process.env.__NULLSTACK_CLI_ENVIRONMENT,
input: process.env.__NULLSTACK_CLI_INPUT,
disk,
trace,
})
const compiler = webpack(webpackConfig)
const webpackDevMiddlewareOptions = {
publicPath: '/',
writeToDisk: disk,
}
server.use(async (_request, _response, next) => {
waitCompiler(next)
})
const instance = webpackDevMiddleware(compiler, webpackDevMiddlewareOptions)
instance.waitUntilValid(async () => {
progress.stop()
console.info(
'\x1b[36m%s\x1b[0m',
`\n 🚀 Your application is ready at http://${process.env.NULLSTACK_PROJECT_DOMAIN}:${process.env.NULLSTACK_SERVER_PORT || process.env.PORT || 3000}\n`,
)
if (disk) {
const content = await server.prerender('/')
const target = `${process.cwd()}/.development/index.html`
writeFileSync(target, content)
}
})
server.use(instance)
const webpackHotMiddleware = __non_webpack_require__(resolve(`webpack-hot-middleware`))
const webpackHotMiddlewareOptions = { log: false, path: '/nullstack/hmr', noinfo: true, quiet: true }
server.use(webpackHotMiddleware(compiler, webpackHotMiddlewareOptions))
}
}