UNPKG

2.23 kBJavaScriptView Raw
1'use strict';
2
3const weblog = require('webpack-log');
4
5module.exports = function ctx(compiler, options) {
6 const context = {
7 state: false,
8 webpackStats: null,
9 callbacks: [],
10 options,
11 compiler,
12 watching: null,
13 forceRebuild: false
14 };
15
16 if (options.logger) {
17 context.log = options.logger;
18 } else {
19 context.log = weblog({
20 level: options.logLevel || 'info',
21 name: 'wdm',
22 timestamp: options.logTime
23 });
24 }
25
26 const { log } = context;
27
28 function done(stats) {
29 // We are now on valid state
30 context.state = true;
31 context.webpackStats = stats;
32
33 // Do the stuff in nextTick, because bundle may be invalidated
34 // if a change happened while compiling
35 process.nextTick(() => {
36 // check if still in valid state
37 if (!context.state) {
38 return;
39 }
40
41 // print webpack output
42 context.options.reporter(context.options, {
43 log,
44 state: true,
45 stats
46 });
47
48 // execute callback that are delayed
49 const cbs = context.callbacks;
50 context.callbacks = [];
51 cbs.forEach((cb) => {
52 cb(stats);
53 });
54 });
55
56 // In lazy mode, we may issue another rebuild
57 if (context.forceRebuild) {
58 context.forceRebuild = false;
59 rebuild();
60 }
61 }
62
63 function invalid(...args) {
64 if (context.state) {
65 context.options.reporter(context.options, {
66 log,
67 state: false
68 });
69 }
70
71 // We are now in invalid state
72 context.state = false;
73 // resolve async
74 if (args.length === 2 && typeof args[1] === 'function') {
75 const [, callback] = args;
76 callback();
77 }
78 }
79
80 function rebuild() {
81 if (context.state) {
82 context.state = false;
83 context.compiler.run((err) => {
84 if (err) {
85 log.error(err.stack || err);
86 if (err.details) {
87 log.error(err.details);
88 }
89 }
90 });
91 } else {
92 context.forceRebuild = true;
93 }
94 }
95
96 context.rebuild = rebuild;
97 context.compiler.plugin('done', done);
98 context.compiler.plugin('invalid', invalid);
99 context.compiler.plugin('watch-run', invalid);
100 context.compiler.plugin('run', invalid);
101
102 return context;
103};