1
|
'use strict';
|
2
|
|
3
|
const mime = require('mime');
|
4
|
|
5
|
const createContext = require('./lib/context');
|
6
|
const middleware = require('./lib/middleware');
|
7
|
const reporter = require('./lib/reporter');
|
8
|
const { setFs, toDisk } = require('./lib/fs');
|
9
|
const { getFilenameFromUrl, noop, ready } = require('./lib/util');
|
10
|
|
11
|
const defaults = {
|
12
|
logLevel: 'info',
|
13
|
logTime: false,
|
14
|
logger: null,
|
15
|
mimeTypes: null,
|
16
|
reporter,
|
17
|
stats: {
|
18
|
colors: true,
|
19
|
context: process.cwd(),
|
20
|
},
|
21
|
watchOptions: {
|
22
|
aggregateTimeout: 200,
|
23
|
},
|
24
|
writeToDisk: false,
|
25
|
};
|
26
|
|
27
|
module.exports = function wdm(compiler, opts) {
|
28
|
const options = Object.assign({}, defaults, opts);
|
29
|
|
30
|
// defining custom MIME type
|
31
|
if (options.mimeTypes) {
|
32
|
const typeMap = options.mimeTypes.typeMap || options.mimeTypes;
|
33
|
const force = !!options.mimeTypes.force;
|
34
|
mime.define(typeMap, force);
|
35
|
}
|
36
|
|
37
|
const context = createContext(compiler, options);
|
38
|
|
39
|
// start watching
|
40
|
if (!options.lazy) {
|
41
|
context.watching = compiler.watch(options.watchOptions, (err) => {
|
42
|
if (err) {
|
43
|
context.log.error(err.stack || err);
|
44
|
if (err.details) {
|
45
|
context.log.error(err.details);
|
46
|
}
|
47
|
}
|
48
|
});
|
49
|
} else {
|
50
|
if (typeof options.filename === 'string') {
|
51
|
const filename = options.filename
|
52
|
.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&') // eslint-disable-line no-useless-escape
|
53
|
.replace(/\\\[[a-z]+\\\]/gi, '.+');
|
54
|
|
55
|
options.filename = new RegExp(`^[/]{0,1}${filename}$`);
|
56
|
}
|
57
|
|
58
|
context.state = true;
|
59
|
}
|
60
|
|
61
|
if (options.writeToDisk) {
|
62
|
toDisk(context);
|
63
|
}
|
64
|
|
65
|
setFs(context, compiler);
|
66
|
|
67
|
return Object.assign(middleware(context), {
|
68
|
close(callback) {
|
69
|
// eslint-disable-next-line no-param-reassign
|
70
|
callback = callback || noop;
|
71
|
|
72
|
if (context.watching) {
|
73
|
context.watching.close(callback);
|
74
|
} else {
|
75
|
callback();
|
76
|
}
|
77
|
},
|
78
|
|
79
|
context,
|
80
|
|
81
|
fileSystem: context.fs,
|
82
|
|
83
|
getFilenameFromUrl: getFilenameFromUrl.bind(
|
84
|
this,
|
85
|
context.options.publicPath,
|
86
|
context.compiler
|
87
|
),
|
88
|
|
89
|
invalidate(callback) {
|
90
|
// eslint-disable-next-line no-param-reassign
|
91
|
callback = callback || noop;
|
92
|
|
93
|
if (context.watching) {
|
94
|
ready(context, callback, {});
|
95
|
context.watching.invalidate();
|
96
|
} else {
|
97
|
callback();
|
98
|
}
|
99
|
},
|
100
|
|
101
|
waitUntilValid(callback) {
|
102
|
// eslint-disable-next-line no-param-reassign
|
103
|
callback = callback || noop;
|
104
|
|
105
|
ready(context, callback, {});
|
106
|
},
|
107
|
});
|
108
|
};
|