forked from webpack/webpack-dev-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
83 lines (71 loc) · 2.24 KB
/
middleware.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var mime = require("mime");
var getFilenameFromUrl = require("./lib/GetFilenameFromUrl");
var Shared = require("./lib/Shared");
var pathJoin = require("./lib/PathJoin");
// constructor for the middleware
module.exports = function(compiler, options) {
var context = {
state: false,
webpackStats: undefined,
callbacks: [],
options: options,
compiler: compiler,
watching: undefined,
forceRebuild: false
};
var shared = Shared(context);
// The middleware function
function webpackDevMiddleware(req, res, next) {
function goNext() {
if(!context.options.serverSideRender) return next();
shared.ready(function() {
res.locals.webpackStats = context.webpackStats;
next();
}, req);
}
if(req.method !== "GET") {
return goNext();
}
var filename = getFilenameFromUrl(context.options.publicPath, context.compiler, req.url);
if(filename === false) return goNext();
shared.handleRequest(filename, processRequest, req);
function processRequest() {
try {
var stat = context.fs.statSync(filename);
if(!stat.isFile()) {
if(stat.isDirectory()) {
filename = pathJoin(filename, context.options.index || "index.html");
stat = context.fs.statSync(filename);
if(!stat.isFile()) throw "next";
} else {
throw "next";
}
}
} catch(e) {
return goNext();
}
// server content
var content = context.fs.readFileSync(filename);
content = shared.handleRangeHeaders(content, req, res);
res.setHeader("Content-Type", mime.lookup(filename) + "; charset=UTF-8");
res.setHeader("Content-Length", content.length);
if(context.options.headers) {
for(var name in context.options.headers) {
res.setHeader(name, context.options.headers[name]);
}
}
if(res.send) res.send(content);
else res.end(content);
}
}
webpackDevMiddleware.getFilenameFromUrl = getFilenameFromUrl.bind(this, context.options.publicPath, context.compiler);
webpackDevMiddleware.waitUntilValid = shared.waitUntilValid;
webpackDevMiddleware.invalidate = shared.invalidate;
webpackDevMiddleware.close = shared.close;
webpackDevMiddleware.fileSystem = context.fs;
return webpackDevMiddleware;
};