UNPKG

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