1 | 'use strict';
|
2 |
|
3 | const weblog = require('webpack-log');
|
4 |
|
5 | module.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 |
|
30 | context.state = true;
|
31 | context.webpackStats = stats;
|
32 |
|
33 |
|
34 |
|
35 | process.nextTick(() => {
|
36 |
|
37 | if (!context.state) {
|
38 | return;
|
39 | }
|
40 |
|
41 |
|
42 | context.options.reporter(context.options, {
|
43 | log,
|
44 | state: true,
|
45 | stats
|
46 | });
|
47 |
|
48 |
|
49 | const cbs = context.callbacks;
|
50 | context.callbacks = [];
|
51 | cbs.forEach((cb) => {
|
52 | cb(stats);
|
53 | });
|
54 | });
|
55 |
|
56 |
|
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 |
|
72 | context.state = false;
|
73 |
|
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 | };
|