Skip to content

Commit 09e1697

Browse files
committed
feat(server): 采用新的 compile & watch 机制
1 parent d983709 commit 09e1697

File tree

8 files changed

+228
-262
lines changed

8 files changed

+228
-262
lines changed

lib/commands/server.js

Lines changed: 158 additions & 151 deletions
Large diffs are not rendered by default.

lib/global.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
require('colors');
44

5-
global.spinner = require('ora')('Loading unicorns');
5+
global.spinner = require('ora')();
66
global.fs = require('fs');
77
global.sysPath = require('path');
88
global.async = require('async');

lib/plugins/compileInfoPlugin.js

Lines changed: 4 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -61,39 +61,17 @@ DashboardPlugin.prototype.apply = function (compiler) {
6161

6262
var dateFormat = 'YY.MM.DD HH:mm:ss';
6363
if (stats.hasErrors()) {
64-
process.stdout && process.stdout.write('\x1b[90m' + '[' + moment().format(dateFormat) + ']' + '\x1b[0m');
65-
error('Compile Failed.');
66-
} else {}
67-
// process.stdout && process.stdout.write('\x1b[90m' + '[' + (moment().format(dateFormat)) + ']' + '\x1b[0m');
68-
// success('Compile Succeed.');
69-
64+
spinner.text = '\x1b[90m' + '[' + moment().format(dateFormat) + ']' + '\x1b[0m' + ' Compile Failed.';
65+
spinner.fail();
66+
spinner.text = '';
67+
}
7068

71-
// self.logText.log(formatOutput(stats));
72-
// self.moduleTable.setData(formatModules(stats));
73-
// self.assetTable.setData(formatAssets(stats));
7469
if (formatOutput(stats)) {
7570
console.log(formatOutput(stats)); // eslint-disable-line
7671
}
77-
// console.log(formatModules(stats));
78-
// console.log(formatAssets(stats));
7972

8073
break;
8174
}
82-
// case 'log':
83-
// {
84-
// self.logText.log(data.value);
85-
// break;
86-
// }
87-
// case 'error':
88-
// {
89-
// self.logText.log("{red-fg}" + data.value + "{/}");
90-
// break;
91-
// }
92-
// case 'clear':
93-
// {
94-
// self.logText.setContent('');
95-
// break;
96-
// }
9775
}
9876
});
9977
};

lib/plugins/progressBarPlugin.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@ module.exports = new ProgressBarPlugin();
66

77
function ProgressBarPlugin() {
88
return new webpack.ProgressPlugin(function (percent, msg) {
9-
if (percent === 0) {
10-
spinner.start();
11-
} else if (msg === 'emit') {
12-
spinner.stop();
13-
}
9+
spinner.start();
1410

1511
if (msg) {
1612
spinner.text = '[Bundler] ' + msg;
13+
if(msg === 'emit') {
14+
setTimeout(() => {
15+
spinner.stop().clear();
16+
}, 100)
17+
}
1718
}
1819
});
19-
}
20+
}

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@
4646
"style-loader": "^0.13.1",
4747
"through2": "^2.0.1",
4848
"webpack": "^1.13.1",
49-
"webpack-dev-middleware": "^1.6.1",
5049
"webpack-md5-hash": "0.0.5"
5150
},
5251
"repository": {

src/commands/server.js

Lines changed: 54 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@ let connect = require('connect'),
99
serveIndex = require('serve-index'),
1010
moment = require('moment'),
1111
child_process = require('child_process'),
12-
requireg = require('requireg'),
13-
webpackDevMiddleware = require('webpack-dev-middleware');
12+
requireg = require('requireg');
1413

1514
let Manager = require('../modules/manager.js');
1615
let UtilFs = require('../utils/fs.js');
@@ -40,8 +39,7 @@ exports.run = (options) => {
4039
isCompilingAll = options.a || options.all,
4140
port = options.p || options.port || 80;
4241

43-
let isWatcherRunning = false,
44-
middlewareCache = {},
42+
let middlewareCache = {},
4543
promiseCache = {},
4644
watchCacheNames = {};
4745

@@ -64,10 +62,11 @@ exports.run = (options) => {
6462
res.end = end;
6563
res.end(chunk, encoding);
6664
const format = '%date %status %method %url (%route%contentLength%time)';
67-
const message = parse(req, res, format);
65+
const parseResult = parse(req, res, format);
6866
return process.nextTick(() => {
69-
spinner.text = message;
70-
return spinner.succeed();
67+
spinner.text = parseResult.message;
68+
parseResult.status >= 400 ? spinner.fail() : spinner.succeed();
69+
spinner.text = '';
7170
});
7271
};
7372

@@ -102,7 +101,11 @@ exports.run = (options) => {
102101
format = format.replace(/%route/g, '\x1b[90m' + (req.route ? req.route.path + ' ' : '\x1b[31m') + '\x1b[0m');
103102
format = format.replace(/%contentLength/g, '\x1b[90m' + contentLength + '\x1b[31m' + '\x1b[0m');
104103
format = format.replace(/%(date|time)/g, '\x1b[90m' + (new Date - req._startTime) + 'ms\x1b[0m');
105-
return format;
104+
105+
return {
106+
message: format,
107+
status: res.statusCode
108+
};
106109
}
107110

108111
return next();
@@ -148,18 +151,16 @@ exports.run = (options) => {
148151

149152
// 处理prd资源
150153
if (keys[2] === 'prd') {
151-
const requestUrl = '/' + keys.slice(3).join('/').replace(/(\@[\d\w]+)?\.(js|css)/, '.$2');
154+
// 去掉 query & 版本号
155+
const requestUrl = keys.slice(3).join('/').replace(/\?[\w=&]+$/, '').replace('.map', '');
156+
152157
// 只编译所请求的资源
153158
if (!isCompilingAll) {
154-
// 去掉版本号和打头的"/"
155-
let pureSourcePath = requestUrl.replace(/@[\d\w]+(?=\.\w+$)/, '');
156-
pureSourcePath = pureSourcePath[0] === '/' ? pureSourcePath.slice(1) : pureSourcePath;
157159

158-
// 去掉url query
159-
pureSourcePath = pureSourcePath.replace(/\?[\w=&]+$/, '');
160+
let requestUrlNoVer = requestUrl.replace(/@[\d\w]+(?=\.\w+$)/, '');
160161

161-
// 从编译cache中取,map文件不必生成重复middleware
162-
const cacheId = sysPath.join(projectName, pureSourcePath.replace('.map', ''));
162+
// 从编译cache中取,map文件不必生成重复middleware TODO
163+
const cacheId = sysPath.join(projectName, requestUrlNoVer);
163164
let middleware = middlewareCache[cacheId];
164165

165166
if (!middleware) {
@@ -168,10 +169,11 @@ exports.run = (options) => {
168169
if (project.check()) {
169170
compiler = project.getServerCompiler(function (config) {
170171
let nextConfig = extend({}, config);
171-
// entry应该是个空对象, 这样如果没有找到请求对应的entry, 就不会编译全部入口
172+
173+
// entry 应该是个空对象, 这样如果没有找到请求对应的 entry, 就不会编译全部入口
172174
nextConfig.entry = {};
173175

174-
// 将webpack entry设置为当前请求的资源
176+
// 将 webpack entry 设置为当前请求的资源
175177
Object.keys(config.entry).map((entryKey) => {
176178
const entryItem = config.entry[entryKey];
177179

@@ -184,15 +186,22 @@ exports.run = (options) => {
184186
entryPath = entryItem;
185187
}
186188

189+
// 将入口的 .scss/.less 后缀替换为.css
187190
const cssReg = new RegExp('\\' + config.entryExtNames.css.join('|\\'));
188-
entryPath = entryPath.replace(cssReg, '.css'); // 将入口的.scss/.less后缀替换为.css
191+
entryPath = entryPath.replace(cssReg, '.css');
189192

190-
// 如果是 ykit 处理过的样式文件
193+
// 如果是 ykit 处理过的样式文件,将其变为正常的请求路径(../.ykit_cache/main/index.css.js => main/index.css)
191194
if(entryPath.indexOf('.css.js') && entryPath.indexOf('.ykit_cache/') > 1) {
192195
entryPath = entryPath.split('.ykit_cache/')[1].replace('.css.js', '.css');
193196
}
194197

195-
isRequestingEntry = sysPath.normalize(entryPath) === sysPath.normalize(pureSourcePath);
198+
// 判断所请求的资源是否在入口配置中
199+
if(sysPath.normalize(entryPath) === sysPath.normalize(requestUrl)) {
200+
isRequestingEntry = true;
201+
} else if(sysPath.normalize(entryPath) === sysPath.normalize(requestUrlNoVer)) {
202+
req.url = req.url.replace(/@[\d\w]+(?=\.\w+$)/, '');
203+
isRequestingEntry = true;
204+
}
196205

197206
if (isRequestingEntry) {
198207
nextConfig.entry = {
@@ -207,36 +216,34 @@ exports.run = (options) => {
207216
return nextConfig;
208217
});
209218

210-
isWatcherRunning = false;
211-
212219
compiler.watch({}, (err) => {
213220
if(err) {
214221
error(err);
215222
} else {
223+
middlewareCache[cacheId] = req.url;
216224
next();
217225
}
218226
});
219227

220-
// if (!middlewareCache[cacheId]) {
221-
// middleware = middlewareCache[cacheId] = webpackDevMiddleware(compiler, { quiet: true });
222-
// middleware(req, res, next);
223-
// } else {
224-
// next();
225-
// }
226-
227228
// 检测config文件变化
228-
// watchConfig(project, middleware, cacheId);
229+
watchConfig(project, middleware, cacheId);
229230
} else {
230231
next();
231232
}
232233
} else {
233-
middleware(req, res, next);
234+
req.url = middleware;
235+
setTimeout(() => {
236+
next();
237+
}, 300);
234238
}
235239
} else { // 一次编译全部资源
236240
let middleware = middlewareCache[projectName],
237241
compilerPromise = promiseCache[projectName],
238242
project = Manager.getProject(projectCwd, { cache: false });
239243

244+
// 统一去掉版本号
245+
req.url = req.url.replace(/@[\d\w]+(?=\.\w+$)/, '');
246+
240247
// 如果entry发生变化,则需要进行重新编译
241248
const nextEntry = extend({}, project.config._config.entry);
242249
if (compilerPromise && compilerPromise.entry) {
@@ -266,22 +273,23 @@ exports.run = (options) => {
266273
promiseCache[projectName].entry = extend({}, nextEntry);
267274

268275
if (project.check()) {
269-
compiler = project.getServerCompiler(function (config) {
276+
compiler = project.getServerCompiler((config) => {
270277
config.plugins.push(require('../plugins/progressBarPlugin.js'));
278+
config.plugins.push(require('../plugins/compileInfoPlugin.js'));
271279
return config;
272280
});
273281

274-
// compiler complete
275-
if (!middlewareCache[projectName]) {
276-
middleware = middlewareCache[projectName] = webpackDevMiddleware(compiler, { quiet: true });
277-
278-
// 输出server运行中 error/warning 信息
282+
compiler.watch({}, (err) => {
279283
creatingCompiler = false;
280-
middleware(req, res, next);
281-
resolve(middleware);
282-
} else {
283-
next();
284-
}
284+
285+
if(err) {
286+
error(err);
287+
} else {
288+
middlewareCache[projectName] = projectName;
289+
resolve();
290+
next();
291+
}
292+
});
285293

286294
// 检测config文件变化
287295
watchConfig(project, middleware, projectName);
@@ -290,8 +298,8 @@ exports.run = (options) => {
290298
}
291299
} else {
292300
if (compilerPromise) {
293-
compilerPromise.then((middleware) => {
294-
middleware(req, res, next);
301+
compilerPromise.then(() => {
302+
next();
295303
});
296304
} else {
297305
next();
@@ -362,12 +370,7 @@ exports.run = (options) => {
362370
function exitHandler() {
363371
// cleanup
364372
proxyProcess && proxyProcess.kill('SIGINT');
365-
366-
if (isWatcherRunning) {
367-
process.kill(process.pid, 'SIGKILL');
368-
} else {
369-
process.exit(0);
370-
}
373+
process.exit(0);
371374
}
372375

373376
// 监测配置文件变化

src/global.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
require('colors');
44

5-
global.spinner = require('ora')('Loading unicorns');
5+
global.spinner = require('ora')();
66
global.fs = require('fs');
77
global.sysPath = require('path');
88
global.async = require('async');

src/plugins/compileInfoPlugin.js

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -63,39 +63,17 @@ DashboardPlugin.prototype.apply = function(compiler) {
6363

6464
const dateFormat = 'YY.MM.DD HH:mm:ss';
6565
if (stats.hasErrors()) {
66-
process.stdout && process.stdout.write('\x1b[90m' + '[' + (moment().format(dateFormat)) + ']' + '\x1b[0m');
67-
error('Compile Failed.');
68-
} else {
69-
// process.stdout && process.stdout.write('\x1b[90m' + '[' + (moment().format(dateFormat)) + ']' + '\x1b[0m');
70-
// success('Compile Succeed.');
66+
spinner.text = '\x1b[90m' + '[' + (moment().format(dateFormat)) + ']' + '\x1b[0m' + ' Compile Failed.';
67+
spinner.fail();
68+
spinner.text = '';
7169
}
7270

73-
// self.logText.log(formatOutput(stats));
74-
// self.moduleTable.setData(formatModules(stats));
75-
// self.assetTable.setData(formatAssets(stats));
7671
if(formatOutput(stats)) {
7772
console.log(formatOutput(stats)); // eslint-disable-line
7873
}
79-
// console.log(formatModules(stats));
80-
// console.log(formatAssets(stats));
8174

8275
break;
8376
}
84-
// case 'log':
85-
// {
86-
// self.logText.log(data.value);
87-
// break;
88-
// }
89-
// case 'error':
90-
// {
91-
// self.logText.log("{red-fg}" + data.value + "{/}");
92-
// break;
93-
// }
94-
// case 'clear':
95-
// {
96-
// self.logText.setContent('');
97-
// break;
98-
// }
9977
}
10078
});
10179
};

0 commit comments

Comments
 (0)