Projekt

Obecné

Profil

Stáhnout (2.26 KB) Statistiky
| Větev: | Revize:
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
    // 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(callback) {
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
    if (typeof callback === 'function') {
74
      callback();
75
    }
76
  }
77

    
78
  function rebuild() {
79
    if (context.state) {
80
      context.state = false;
81
      context.compiler.run((err) => {
82
        if (err) {
83
          log.error(err.stack || err);
84
          if (err.details) {
85
            log.error(err.details);
86
          }
87
        }
88
      });
89
    } else {
90
      context.forceRebuild = true;
91
    }
92
  }
93

    
94
  context.rebuild = rebuild;
95
  context.compiler.hooks.invalid.tap('WebpackDevMiddleware', invalid);
96
  context.compiler.hooks.run.tap('WebpackDevMiddleware', invalid);
97
  context.compiler.hooks.done.tap('WebpackDevMiddleware', done);
98
  context.compiler.hooks.watchRun.tap(
99
    'WebpackDevMiddleware',
100
    (comp, callback) => {
101
      invalid(callback);
102
    }
103
  );
104

    
105
  return context;
106
};
(2-2/6)