forked from webpack/webpack-dev-middleware
-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.js
193 lines (165 loc) · 4.97 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var path = require("path");
var MemoryFileSystem = require("memory-fs");
var mime = require("mime");
// constructor for the middleware
module.exports = function(compiler, options) {
if(!options) options = {};
if(options.watchDelay === undefined) options.watchDelay = 200;
if(typeof options.stats === "undefined") options.stats = {};
if(!options.stats.context) options.stats.context = process.cwd();
// store our files in memory
var files = {};
var fs = compiler.outputFileSystem = new MemoryFileSystem();
compiler.plugin("done", function(stats) {
// We are now on valid state
state = true;
// Do the stuff in nextTick, because bundle may be invalidated
// if a change happend while compiling
process.nextTick(function() {
// check if still in valid state
if(!state) return;
// print webpack output
var displayStats = (!options.quiet && options.stats !== false);
if(displayStats &&
!(stats.hasErrors() || stats.hasWarnings()) &&
options.noInfo)
displayStats = false;
if(displayStats) {
console.log(stats.toString(options.stats));
}
if (!options.noInfo && !options.quiet)
console.info("webpack: bundle is now VALID.");
// execute callback that are delayed
var cbs = callbacks;
callbacks = [];
cbs.forEach(function continueBecauseBundleAvailible(cb) {
cb();
});
});
// In lazy mode, we may issue another rebuild
if(forceRebuild) {
forceRebuild = false;
rebuild();
}
});
// on compiling
function invalidPlugin() {
if(state && (!options.noInfo && !options.quiet))
console.info("webpack: bundle is now INVALID.");
// We are now in invalid state
state = false;
}
compiler.plugin("invalid", invalidPlugin);
compiler.plugin("compile", invalidPlugin);
// the state, false: bundle invalid, true: bundle valid
var state = false;
// in lazy mode, rebuild automatically
var forceRebuild = false;
// delayed callback
var callbacks = [];
// wait for bundle valid
function ready(fn, req) {
if(state) return fn();
if(!options.noInfo && !options.quiet)
console.log("webpack: wait until bundle finished: " + req.url);
callbacks.push(fn);
}
// start watching
if(!options.lazy) {
var watching = compiler.watch(options.watchDelay, function(err) {
if(err) throw err;
});
} else {
state = true;
}
function rebuild() {
if(state) {
state = false;
compiler.run(function(err) {
if(err) throw err;
});
} else {
forceRebuild = true;
}
}
function pathJoin(a, b) {
return a == "/" ? "/" + b : (a||"") + "/" + b;
}
function getFilenameFromUrl(url) {
// localPreview is the folder our bundle should be in
var localPrefixes = options.publicPath || ["/"];
var filename;
if (typeof localPrefixes == 'string') {
localPrefixes = [ localPrefixes ];
}
for (var i in localPrefixes) {
var localPrefix = localPrefixes[i];
if(url.indexOf(localPrefix) !== 0) {
if(/^(https?:)?\/\//.test(localPrefix)) {
localPrefix = "/" + localPrefix.replace(/^(https?:)?\/\/[^\/]+\//, "");
// fast exit if another directory requested
if(url.indexOf(localPrefix) !== 0) continue;
} else continue;
}
// get filename from request
filename = url.substr(localPrefix.length);
if(filename.indexOf("?") >= 0) {
filename = filename.substr(0, filename.indexOf("?"));
}
}
if (!filename) {
return false;
}
return filename ? pathJoin(compiler.outputPath, filename) : compiler.outputPath;
}
// The middleware function
function webpackDevMiddleware(req, res, next) {
var filename = getFilenameFromUrl(req.url);
if (filename === false) return next();
// in lazy mode, rebuild on bundle request
if(options.lazy && filename === pathJoin(compiler.outputPath, options.filename))
rebuild();
// delay the request until we have a vaild bundle
ready(function() {
try {
var stat = fs.statSync(filename);
if(!stat.isFile()) {
if (stat.isDirectory()) {
filename = path.join(filename, "index.html");
stat = fs.statSync(filename);
if(!stat.isFile()) throw "next";
} else {
throw "next";
}
}
} catch(e) {
return next();
}
// server content
var content = fs.readFileSync(filename);
res.setHeader("Access-Control-Allow-Origin", "*"); // To support XHR, etc.
res.setHeader("Content-Type", mime.lookup(filename));
if(options.headers) {
for(var name in options.headers) {
res.setHeader(name, options.headers[name]);
}
}
res.end(content);
}, req);
}
webpackDevMiddleware.getFilenameFromUrl = getFilenameFromUrl;
webpackDevMiddleware.invalidate = function() {
if(watching) watching.invalidate();
};
webpackDevMiddleware.close = function(callback) {
callback = callback || function(){};
if(watching) watching.close(callback);
else callback();
};
webpackDevMiddleware.fileSystem = fs;
return webpackDevMiddleware;
}