-
Notifications
You must be signed in to change notification settings - Fork 220
/
karma-webpack.js
290 lines (245 loc) · 8.22 KB
/
karma-webpack.js
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
/* eslint-disable
max-len,
no-console,
func-style,
*/
var os = require('os')
var _ = require('lodash')
var path = require('path')
var async = require('async')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpack = require('webpack')
var SingleEntryDependency = require('webpack/lib/dependencies/SingleEntryDependency')
var blocked = []
var isBlocked = false
var escapeRegExp = function(str) {
// See details here https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
}
function Plugin(
/* config.webpack */ webpackOptions,
/* config.webpackServer */ webpackServerOptions,
/* config.webpackMiddleware */ webpackMiddlewareOptions,
/* config.basePath */ basePath,
/* config.files */ files,
/* config.frameworks */ frameworks,
/* config.singleRun */ singleRun,
customFileHandlers,
emitter
) {
webpackOptions = _.clone(webpackOptions) || {}
webpackMiddlewareOptions = _.clone(webpackMiddlewareOptions || webpackServerOptions) || {}
var applyOptions = Array.isArray(webpackOptions) ? webpackOptions : [webpackOptions]
var includeIndex = applyOptions.length > 1
applyOptions.forEach(function(webpackOptions, index) {
// The webpack tier owns the watch behavior so we want to force it in the config
webpackOptions.watch = !singleRun
// Webpack 2.1.0-beta.7+ will throw in error if both entry and plugins are not specified in options
// https://github.com/webpack/webpack/commit/b3bc5427969e15fd3663d9a1c57dbd1eb2c94805
if (!webpackOptions.entry) {
webpackOptions.entry = function() {
return {}
}
};
if (!webpackOptions.output) {
webpackOptions.output = {}
};
// When using an array, even of length 1, we want to include the index value for the build.
// This is due to the way that the dev server exposes commonPath for build output.
var indexPath = includeIndex ? `${index}/` : ''
var publicPath = indexPath !== '' ? `${indexPath}/` : ''
// Must have the common _karma_webpack_ prefix on path here to avoid
// https://github.com/webpack/webpack/issues/645
webpackOptions.output.path = path.join(os.tmpdir(), '_karma_webpack_', indexPath, '/')
webpackOptions.output.publicPath = path.join(os.tmpdir(), '_karma_webpack_', publicPath, '/')
webpackOptions.output.filename = '[name]'
if (includeIndex) {
webpackOptions.output.jsonpFunction = `webpackJsonp${index}`
}
webpackOptions.output.chunkFilename = '[id].bundle.js'
})
this.emitter = emitter
this.wrapMocha = frameworks.indexOf('mocha') >= 0 && includeIndex
this.optionsCount = applyOptions.length
this.files = []
this.basePath = basePath
this.waiting = []
var compiler
try {
compiler = webpack(webpackOptions)
} catch (e) {
console.error(e.stack || e)
if (e.details) {
console.error(e.details)
}
throw e
}
var applyPlugins = compiler.compilers || [compiler]
applyPlugins.forEach(function(compiler) {
compiler.plugin('this-compilation', function(compilation, params) {
compilation.dependencyFactories.set(SingleEntryDependency, params.normalModuleFactory)
})
compiler.plugin('make', this.make.bind(this))
}, this);
['invalid', 'watch-run', 'run'].forEach(function(name) {
compiler.plugin(name, function(_, callback) {
isBlocked = true
if (typeof callback === 'function') {
callback()
}
})
})
compiler.plugin('done', function(stats) {
var applyStats = Array.isArray(stats.stats) ? stats.stats : [stats]
var assets = []
var noAssets = false
applyStats.forEach(function(stats) {
stats = stats.toJson()
assets.push(...stats.assets)
if (stats.assets.length === 0) {
noAssets = true
}
})
if (!this.waiting || this.waiting.length === 0) {
this.notifyKarmaAboutChanges()
}
if (this.waiting && !noAssets) {
var w = this.waiting
this.waiting = null
w.forEach(function(cb) {
cb()
})
}
isBlocked = false
for (var i = 0; i < blocked.length; i++) {
blocked[i]()
}
blocked = []
}.bind(this))
compiler.plugin('invalid', function() {
if (!this.waiting) {
this.waiting = []
}
}.bind(this))
webpackMiddlewareOptions.publicPath = path.join(os.tmpdir(), '_karma_webpack_', '/')
var middleware = this.middleware = new webpackDevMiddleware(compiler, webpackMiddlewareOptions)
customFileHandlers.push({
urlRegex: new RegExp(`^${escapeRegExp(webpackMiddlewareOptions.publicPath)}.*`),
handler(req, res) {
middleware(req, res, function() {
res.statusCode = 404
res.end('Not found')
})
}
})
emitter.on('exit', function(done) {
middleware.close()
done()
})
}
Plugin.prototype.notifyKarmaAboutChanges = function() {
// Force a rebuild
this.emitter.refreshFiles()
}
Plugin.prototype.addFile = function(entry) {
if (this.files.indexOf(entry) >= 0) {
return
}
this.files.push(entry)
return true
}
Plugin.prototype.make = function(compilation, callback) {
async.forEach(this.files.slice(), function(file, callback) {
var entry = file
if (this.wrapMocha) {
entry = `${require.resolve('./mocha-env-loader')}!${entry}`
}
var dep = new SingleEntryDependency(entry)
compilation.addEntry('', dep, path.relative(this.basePath, file).replace(/\\/g, '/'), function(err) {
// If the module fails because of an File not found error, remove the test file
if (dep.module && dep.module.error &&
dep.module.error.error &&
dep.module.error.error.code === 'ENOENT') {
this.files = this.files.filter(function(f) {
return file !== f
})
this.middleware.invalidate()
}
callback(err)
}.bind(this))
}.bind(this), callback)
}
Plugin.prototype.readFile = function(file, callback) {
var middleware = this.middleware
var optionsCount = this.optionsCount
var doRead = function() {
if (optionsCount > 1) {
async.times(optionsCount, function(idx, callback) {
middleware.fileSystem.readFile(path.join(os.tmpdir(), '_karma_webpack_', String(idx), file.replace(/\\/g, '/')), callback)
}, function(err, contents) {
if (err) {
return callback(err)
};
contents = contents.reduce(function(arr, x) {
if (!arr) {
return [x]
};
arr.push(new Buffer('\n'), x)
return arr
}, null)
callback(null, Buffer.concat(contents))
})
} else {
try {
var fileContents = middleware.fileSystem.readFileSync(path.join(os.tmpdir(), '_karma_webpack_', file.replace(/\\/g, '/')))
callback(undefined, fileContents)
} catch (e) {
// If this is an error from `readFileSync` method, wait for the next tick.
// Credit #69 @mewdriller
if (e.code === 'ENOENT') {
// eslint-disable-line quotes
this.waiting = [process.nextTick.bind(process, this.readFile.bind(this, file, callback))]
// throw otherwise
} else {
callback(e)
}
}
}
}.bind(this)
if (!this.waiting) {
doRead()
} else {
// Retry to read once a build is finished
// do it on process.nextTick to catch changes while building
this.waiting.push(process.nextTick.bind(process, this.readFile.bind(this, file, callback)))
}
}
function createPreprocesor(/* config.basePath */ basePath, webpackPlugin) {
return function(content, file, done) {
if (webpackPlugin.addFile(file.originalPath)) {
// recompile as we have an asset that we have not seen before
webpackPlugin.middleware.invalidate()
}
// read blocks until bundle is done
webpackPlugin.readFile(path.relative(basePath, file.originalPath), function(err, content) {
if (err) {
throw err
}
done(err, content && content.toString())
})
}
}
function createWebpackBlocker() {
return function(request, response, next) {
if (isBlocked) {
blocked.push(next)
} else {
next()
}
}
}
module.exports = {
webpackPlugin: ['type', Plugin],
'preprocessor:webpack': ['factory', createPreprocesor],
'middleware:webpackBlocker': ['factory', createWebpackBlocker]
}