-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (61 loc) · 1.84 KB
/
server.js
File metadata and controls
71 lines (61 loc) · 1.84 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
var fs = require('fs')
var path = require('path')
var webpack = require('webpack')
var WebpackDevServer = require('webpack-dev-server')
var config = require('./webpack.config')
require('shelljs/global')
var serverPort = 54999
var devPort = 8082
var exec = require('child_process').exec
var cmdStr = 'cross-env PORT=' + serverPort + ' supervisor ./bin/www'
exec(cmdStr, function (err, stdout, stderr) {
if (err) {
console.error(err)
} else {
console.log(stdout)
}
})
for (var i in config.entry) {
config.entry[i].unshift('webpack-dev-server/client?http://localhost:' + devPort, 'webpack/hot/dev-server')
}
config.plugins.push(new webpack.HotModuleReplacementPlugin())
var proxy = {
'*': 'http://localhost:' + serverPort
}
var compiler = webpack(config)
// 启动服务
var app = new WebpackDevServer(compiler, {
publicPath: '/static/',
hot: true,
proxy: proxy
})
var viewPath = path.join(__dirname, 'views')
rm('-rf', viewPath)
// 在源码有更新时,更新模板
compiler.plugin('emit', function (compilation, cb) {
for (var filename in compilation.assets) {
if (filename.endsWith('.html')) {
let filepath = path.resolve(viewPath, filename)
let dirname = path.dirname(filepath)
if (!fs.existsSync(dirname)) {
mkdir('-p', dirname)
}
fs.writeFile(filepath, compilation.assets[filename].source())
}
}
cb()
})
// 当页面模板有改变时,强制刷新页面
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
// todo 刷新浏览器
/**
* 实际项目中,应该使用webpack-dev-middleware和webpack-hot-middleware中间件,
* 结合node库express/koa等使用。
*/
cb()
})
})
app.listen(devPort, function () {
console.log('dev server on http://0.0.0.0:' + devPort + '\n')
})