forked from fullstack-hy2020/create-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (55 loc) · 1.94 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
require('dotenv').config()
require('module-alias/register')
const chokidar = require('chokidar')
const express = require('express')
const path = require('path')
require('express-async-errors')
const { PORT, inProduction } = require('@util/common')
const app = express()
// Require is here so we can delete it from cache when files change (*)
app.use('/api', (req, res, next) => require('@root/server')(req, res, next)) // eslint-disable-line
/**
* Use "hot loading" in backend
*/
const watcher = chokidar.watch('server') // Watch server folder
watcher.on('ready', () => {
watcher.on('all', () => {
Object.keys(require.cache).forEach((id) => {
if (id.includes('server')) delete require.cache[id] // Delete all require caches that point to server folder (*)
})
})
})
/**
* For frontend use hot loading when in development, else serve the static content
*/
if (!inProduction) {
/* eslint-disable */
const webpack = require('webpack')
const middleware = require('webpack-dev-middleware')
const hotMiddleWare = require('webpack-hot-middleware')
const webpackConf = require('@root/webpack.config')
/* eslint-enable */
const compiler = webpack(webpackConf('development', { mode: 'development' }))
const devMiddleware = middleware(compiler)
app.use(devMiddleware)
app.use(hotMiddleWare(compiler))
app.use('*', (req, res, next) => {
const filename = path.join(compiler.outputPath, 'index.html')
devMiddleware.waitUntilValid(() => {
compiler.outputFileSystem.readFile(filename, (err, result) => {
if (err) return next(err)
res.set('content-type', 'text/html')
res.send(result)
return res.end()
})
})
})
} else {
const DIST_PATH = path.resolve(__dirname, './dist')
const INDEX_PATH = path.resolve(DIST_PATH, 'index.html')
app.use(express.static(DIST_PATH))
app.get('*', (req, res) => res.sendFile(INDEX_PATH))
}
app.listen(PORT, () => {
console.log(`Started on port ${PORT}`)
})