dev-server.js
2.59 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const webpack = require('webpack');
const path = require('path');
const MFS = require('memory-fs');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const pkg = require('../package.json');
let clientConfig = require('./webpack.client.conf.js');
let serverConfig = require('./webpack.server.conf.js');
let devMiddleware;
let hotMiddleware;
const _readFile = (fs, file) => {
try {
return fs.readFileSync(path.join(clientConfig.output.path, file), 'utf-8');
} catch (e) {
console.error('file load failure!', file);
}
};
exports.readFile = (file) => {
try {
return devMiddleware.fileSystem.readFileSync(path.join(clientConfig.output.path, file), 'utf-8');
} catch (e) {
return false;
}
};
exports.publish = (data) => {
return hotMiddleware.publish(data);
};
exports.devServer = (app, cb) => {
let resolve;
let realyPromise = new Promise(r => {
resolve = r;
});
let ready = (...args) => {
resolve();
cb(...args);
};
clientConfig.entry.app = ['./build/client-hot.js', clientConfig.entry.app];
clientConfig.output.publicPath = 'http://m.yohoblk.com:6005/';
clientConfig.output.filename = '[name].js';
clientConfig.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
);
const clientCompiler = webpack(clientConfig);
devMiddleware = webpackDevMiddleware(clientCompiler, {
publicPath: clientConfig.output.publicPath,
quiet: true,
headers: {
'Access-Control-Allow-Origin': '*'
}
});
app.use(devMiddleware);
let bundle, clientManifest;
clientCompiler.plugin('done', stats => {
stats = stats.toJson();
stats.errors.forEach(error => console.log(error));
stats.warnings.forEach(warning => console.log(warning));
if (stats.errors.length) {
return;
}
clientManifest = JSON.parse(_readFile(devMiddleware.fileSystem, `yoho-ssr-client-${pkg.version}.json`));
if (bundle) {
ready({bundle, options: {clientManifest}});
}
});
hotMiddleware = webpackHotMiddleware(clientCompiler, { heartbeat: 5000 });
app.use(hotMiddleware);
const serverCompiler = webpack(serverConfig);
let mfs = new MFS();
serverCompiler.outputFileSystem = mfs;
serverCompiler.watch({}, (err, stats) => {
if (err) {
throw err;
}
stats = stats.toJson();
if (stats.errors.length) {
return;
}
bundle = JSON.parse(_readFile(mfs, `yoho-ssr-server-${pkg.version}.json`));
if (clientManifest) {
ready({bundle, options: {clientManifest}});
}
});
return realyPromise;
};