xwt
6 小时以前 2884be21228fb6b9ed801d732813e8df507cae23
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
const utils = require('./utils')
 
const uniqueBy = utils.uniqueBy
 
class WebpackErrorsPlugin {
  constructor (options) {
    options = options || {}
    this.sourceRoot = options.sourceRoot
    this.onErrors = options.onErrors
    this.onWarnings = options.onWarnings
  }
 
  apply (compiler) {
    const doneFn = stats => {
      const hasErrors = stats.hasErrors()
      const hasWarnings = stats.hasWarnings()
 
      if (hasErrors && this.onErrors) {
        this.onErrors(extractErrorsFromStats(stats, 'errors'))
        return
      }
 
      if (hasWarnings && this.onWarnings) {
        this.onWarnings(extractErrorsFromStats(stats, 'warnings'))
      }
    }
 
    if (compiler.hooks) {
      const plugin = {
        name: 'UniAppErrorsWebpackPlugin'
      }
      compiler.hooks.done.tap(plugin, doneFn)
    } else {
      compiler.plugin('done', doneFn)
    }
  }
}
 
function extractErrorsFromStats (stats, type) {
  if (isMultiStats(stats)) {
    const errors = stats.stats
      .reduce((errors, stats) => errors.concat(extractErrorsFromStats(stats, type)), [])
    // Dedupe to avoid showing the same error many times when multiple
    // compilers depend on the same module.
    return uniqueBy(errors, error => error.message)
  }
  return stats.compilation[type]
}
 
function isMultiStats (stats) {
  return stats.stats
}
 
module.exports = WebpackErrorsPlugin