# 三.compiler

关键钩子 钩子类型 钩子参数 作用
beforeRun AsyncSeriesHook Compiler 运行前的准备活动,主要启用了文件读取的功能。
run AsyncSeriesHook Compiler “机器”已经跑起来了,在编译之前有缓存,则启用缓存,这样可以提高效率。
beforeCompile AsyncSeriesHook params 开始编译前的准备,创建的ModuleFactory,创建Compilation,并绑定ModuleFactory到Compilation上。
compile SyncHook params 编译了
make AsyncParallelHook compilation 从Compilation的addEntry函数,开始构建模块
afterCompile AsyncSeriesHook compilation 编译结束了
shouldEmit SyncBailHook compilation 获取compilation发来的电报,确定编译时候成功,是否可以开始输出了。
emit AsyncSeriesHook compilation 输出文件了
afterEmit AsyncSeriesHook compilation 输出完毕
done AsyncSeriesHook Status 无论成功与否,一切已尘埃落定。
compiler = new Compiler()
1

Compiler.js

function Compiler() {
  Tapable.call(this)

  this.outputPath = ""
  this.outputFileSystem = null
  this.inputFileSystem = null

  this.recordsInputPath = null
  this.recordsOutputPath = null
  this.records = {}

  this.fileTimestamps = {}
  this.contextTimestamps = {}

  this.resolvers = {
    normal: null,
    loader: null,
    context: null,
  }
  var deprecationReported = false
  this.parser = {
    plugin: function(hook, fn) {
      if (!deprecationReported) {
        console.warn(
          "webpack: Using compiler.parser is deprecated.\n" +
            'Use compiler.plugin("compilation", function(compilation, data) {\n  data.normalModuleFactory.plugin("parser", function(parser, options) { parser.plugin(/* ... */); });\n}); instead. ' +
            "It was called " +
            new Error().stack.split("\n")[2].trim() +
            "."
        )
        deprecationReported = true
      }
      this.plugin("compilation", function(compilation, data) {
        data.normalModuleFactory.plugin("parser", function(parser) {
          parser.plugin(hook, fn)
        })
      })
    }.bind(this),
    apply: function() {
      var args = arguments
      if (!deprecationReported) {
        console.warn(
          "webpack: Using compiler.parser is deprecated.\n" +
            'Use compiler.plugin("compilation", function(compilation, data) {\n  data.normalModuleFactory.plugin("parser", function(parser, options) { parser.apply(/* ... */); });\n}); instead. ' +
            "It was called " +
            new Error().stack.split("\n")[2].trim() +
            "."
        )
        deprecationReported = true
      }
      this.plugin("compilation", function(compilation, data) {
        data.normalModuleFactory.plugin("parser", function(parser) {
          parser.apply.apply(parser, args)
        })
      })
    }.bind(this),
  }

  this.options = {}
}
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
55
56
57
58
59
60
Compiler.prototype = Object.create(Tapable.prototype)
Compiler.prototype.constructor = Compiler

Compiler.Watching = Watching
Compiler.prototype.watch = function(watchOptions, handler) {
  this.fileTimestamps = {}
  this.contextTimestamps = {}
  var watching = new Watching(this, watchOptions, handler)
  return watching
}

Compiler.prototype.run = function(callback) {
  var self = this
  var startTime = Date.now()

  self.applyPluginsAsync("before-run", self, function(err) {
    if (err) return callback(err)

    self.applyPluginsAsync("run", self, function(err) {
      if (err) return callback(err)

      self.readRecords(function(err) {
        if (err) return callback(err)

        self.compile(function onCompiled(err, compilation) {
          if (err) return callback(err)

          if (
            self.applyPluginsBailResult("should-emit", compilation) === false
          ) {
            var stats = new Stats(compilation)
            stats.startTime = startTime
            stats.endTime = Date.now()
            self.applyPlugins("done", stats)
            return callback(null, stats)
          }

          self.emitAssets(compilation, function(err) {
            if (err) return callback(err)

            if (compilation.applyPluginsBailResult("need-additional-pass")) {
              compilation.needAdditionalPass = true

              var stats = new Stats(compilation)
              stats.startTime = startTime
              stats.endTime = Date.now()
              self.applyPlugins("done", stats)

              self.applyPluginsAsync("additional-pass", function(err) {
                if (err) return callback(err)
                self.compile(onCompiled)
              })
              return
            }

            self.emitRecords(function(err) {
              if (err) return callback(err)

              var stats = new Stats(compilation)
              stats.startTime = startTime
              stats.endTime = Date.now()
              self.applyPlugins("done", stats)
              return callback(null, stats)
            })
          })
        })
      })
    })
  })
}

Compiler.prototype.runAsChild = function(callback) {
  this.compile(
    function(err, compilation) {
      if (err) return callback(err)

      this.parentCompilation.children.push(compilation)
      Object.keys(compilation.assets).forEach(
        function(name) {
          this.parentCompilation.assets[name] = compilation.assets[name]
        }.bind(this)
      )

      var entries = Object.keys(compilation.entrypoints)
        .map(function(name) {
          return compilation.entrypoints[name].chunks
        })
        .reduce(function(array, chunks) {
          return array.concat(chunks)
        }, [])

      return callback(null, entries, compilation)
    }.bind(this)
  )
}

Compiler.prototype.purgeInputFileSystem = function() {
  if (this.inputFileSystem && this.inputFileSystem.purge)
    this.inputFileSystem.purge()
}

Compiler.prototype.emitAssets = function(compilation, callback) {
  var outputPath

  this.applyPluginsAsync(
    "emit",
    compilation,
    function(err) {
      if (err) return callback(err)
      outputPath = compilation.getPath(this.outputPath)
      this.outputFileSystem.mkdirp(outputPath, emitFiles.bind(this))
    }.bind(this)
  )

  function emitFiles(err) {
    if (err) return callback(err)

    require("async").forEach(
      Object.keys(compilation.assets),
      function(file, callback) {
        var targetFile = file
        var queryStringIdx = targetFile.indexOf("?")
        if (queryStringIdx >= 0) {
          targetFile = targetFile.substr(0, queryStringIdx)
        }

        if (targetFile.match(/\/|\\/)) {
          var dir = path.dirname(targetFile)
          this.outputFileSystem.mkdirp(
            this.outputFileSystem.join(outputPath, dir),
            writeOut.bind(this)
          )
        } else writeOut.call(this)

        function writeOut(err) {
          if (err) return callback(err)
          var targetPath = this.outputFileSystem.join(outputPath, targetFile)
          var source = compilation.assets[file]
          if (source.existsAt === targetPath) {
            source.emitted = false
            return callback()
          }
          var content = source.source()

          if (!Buffer.isBuffer(content)) {
            content = new Buffer(content, "utf8") //eslint-disable-line
          }

          source.existsAt = targetPath
          source.emitted = true
          this.outputFileSystem.writeFile(targetPath, content, callback)
        }
      }.bind(this),
      function(err) {
        if (err) return callback(err)

        afterEmit.call(this)
      }.bind(this)
    )
  }

  function afterEmit() {
    this.applyPluginsAsyncSeries1("after-emit", compilation, function(err) {
      if (err) return callback(err)

      return callback()
    })
  }
}

Compiler.prototype.emitRecords = function emitRecords(callback) {
  if (!this.recordsOutputPath) return callback()
  var idx1 = this.recordsOutputPath.lastIndexOf("/")
  var idx2 = this.recordsOutputPath.lastIndexOf("\\")
  var recordsOutputPathDirectory = null
  if (idx1 > idx2)
    recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1)
  if (idx1 < idx2)
    recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2)
  if (!recordsOutputPathDirectory) return writeFile.call(this)
  this.outputFileSystem.mkdirp(
    recordsOutputPathDirectory,
    function(err) {
      if (err) return callback(err)
      writeFile.call(this)
    }.bind(this)
  )

  function writeFile() {
    this.outputFileSystem.writeFile(
      this.recordsOutputPath,
      JSON.stringify(this.records, undefined, 2),
      callback
    )
  }
}

Compiler.prototype.readRecords = function readRecords(callback) {
  var self = this
  if (!self.recordsInputPath) {
    self.records = {}
    return callback()
  }
  self.inputFileSystem.stat(self.recordsInputPath, function(err) {
    // It doesn't exist
    // We can ignore self.
    if (err) return callback()

    self.inputFileSystem.readFile(self.recordsInputPath, function(
      err,
      content
    ) {
      if (err) return callback(err)

      try {
        self.records = JSON.parse(content.toString("utf-8"))
      } catch (e) {
        e.message = "Cannot parse records: " + e.message
        return callback(e)
      }

      return callback()
    })
  })
}

Compiler.prototype.createChildCompiler = function(
  compilation,
  compilerName,
  outputOptions,
  plugins
) {
  var childCompiler = new Compiler()
  if (Array.isArray(plugins)) {
    plugins.forEach((plugin) => childCompiler.apply(plugin))
  }
  for (var name in this._plugins) {
    if (
      [
        "make",
        "compile",
        "emit",
        "after-emit",
        "invalid",
        "done",
        "this-compilation",
      ].indexOf(name) < 0
    )
      childCompiler._plugins[name] = this._plugins[name].slice()
  }
  childCompiler.name = compilerName
  childCompiler.outputPath = this.outputPath
  childCompiler.inputFileSystem = this.inputFileSystem
  childCompiler.outputFileSystem = null
  childCompiler.resolvers = this.resolvers
  childCompiler.fileTimestamps = this.fileTimestamps
  childCompiler.contextTimestamps = this.contextTimestamps
  if (!this.records[compilerName]) this.records[compilerName] = []
  this.records[compilerName].push((childCompiler.records = {}))
  childCompiler.options = Object.create(this.options)
  childCompiler.options.output = Object.create(childCompiler.options.output)
  for (name in outputOptions) {
    childCompiler.options.output[name] = outputOptions[name]
  }
  childCompiler.parentCompilation = compilation
  return childCompiler
}

Compiler.prototype.isChild = function() {
  return !!this.parentCompilation
}

Compiler.prototype.createCompilation = function() {
  return new Compilation(this)
}

Compiler.prototype.newCompilation = function(params) {
  var compilation = this.createCompilation()
  compilation.fileTimestamps = this.fileTimestamps
  compilation.contextTimestamps = this.contextTimestamps
  compilation.name = this.name
  compilation.records = this.records
  compilation.compilationDependencies = params.compilationDependencies
  this.applyPlugins("this-compilation", compilation, params)
  this.applyPlugins("compilation", compilation, params)
  return compilation
}

Compiler.prototype.createNormalModuleFactory = function() {
  var normalModuleFactory = new NormalModuleFactory(
    this.options.context,
    this.resolvers,
    this.options.module || {}
  )
  this.applyPlugins("normal-module-factory", normalModuleFactory)
  return normalModuleFactory
}

Compiler.prototype.createContextModuleFactory = function() {
  var contextModuleFactory = new ContextModuleFactory(
    this.resolvers,
    this.inputFileSystem
  )
  this.applyPlugins("context-module-factory", contextModuleFactory)
  return contextModuleFactory
}

Compiler.prototype.newCompilationParams = function() {
  var params = {
    normalModuleFactory: this.createNormalModuleFactory(),
    contextModuleFactory: this.createContextModuleFactory(),
    compilationDependencies: [],
  }
  return params
}

Compiler.prototype.compile = function(callback) {
  var self = this
  var params = self.newCompilationParams()
  self.applyPluginsAsync("before-compile", params, function(err) {
    if (err) return callback(err)

    self.applyPlugins("compile", params)

    var compilation = self.newCompilation(params)

    self.applyPluginsParallel("make", compilation, function(err) {
      if (err) return callback(err)

      compilation.finish()

      compilation.seal(function(err) {
        if (err) return callback(err)

        self.applyPluginsAsync("after-compile", compilation, function(err) {
          if (err) return callback(err)

          return callback(null, compilation)
        })
      })
    })
  })
}
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343