index.js
2.44 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
101
102
103
104
105
106
107
108
'use strict';
const mime = require('mime');
const createContext = require('./lib/context');
const middleware = require('./lib/middleware');
const reporter = require('./lib/reporter');
const { setFs, toDisk } = require('./lib/fs');
const { getFilenameFromUrl, noop, ready } = require('./lib/util');
const defaults = {
logLevel: 'info',
logTime: false,
logger: null,
mimeTypes: null,
reporter,
stats: {
colors: true,
context: process.cwd(),
},
watchOptions: {
aggregateTimeout: 200,
},
writeToDisk: false,
};
module.exports = function wdm(compiler, opts) {
const options = Object.assign({}, defaults, opts);
// defining custom MIME type
if (options.mimeTypes) {
const typeMap = options.mimeTypes.typeMap || options.mimeTypes;
const force = !!options.mimeTypes.force;
mime.define(typeMap, force);
}
const context = createContext(compiler, options);
// start watching
if (!options.lazy) {
context.watching = compiler.watch(options.watchOptions, (err) => {
if (err) {
context.log.error(err.stack || err);
if (err.details) {
context.log.error(err.details);
}
}
});
} else {
if (typeof options.filename === 'string') {
const filename = options.filename
.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&') // eslint-disable-line no-useless-escape
.replace(/\\\[[a-z]+\\\]/gi, '.+');
options.filename = new RegExp(`^[/]{0,1}${filename}$`);
}
context.state = true;
}
if (options.writeToDisk) {
toDisk(context);
}
setFs(context, compiler);
return Object.assign(middleware(context), {
close(callback) {
// eslint-disable-next-line no-param-reassign
callback = callback || noop;
if (context.watching) {
context.watching.close(callback);
} else {
callback();
}
},
context,
fileSystem: context.fs,
getFilenameFromUrl: getFilenameFromUrl.bind(
this,
context.options.publicPath,
context.compiler
),
invalidate(callback) {
// eslint-disable-next-line no-param-reassign
callback = callback || noop;
if (context.watching) {
ready(context, callback, {});
context.watching.invalidate();
} else {
callback();
}
},
waitUntilValid(callback) {
// eslint-disable-next-line no-param-reassign
callback = callback || noop;
ready(context, callback, {});
},
});
};