-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathplugin.js
60 lines (48 loc) · 1.65 KB
/
plugin.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
'use strict'
const fp = require('fastify-plugin')
const { join } = require('path')
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
async function fastifyWebpack (instance, opts) {
if (instance.hasDecorator('webpack')) throw new Error('[fastify-weback-hmr]: fastify.webpack has registered already.')
let { compiler, config, webpackDev = {}, webpackHot = {} } = opts
if (!compiler) {
if (typeof config !== 'object' && !Array.isArray(config)) {
const path = config || join(__dirname, 'webpack.config.js')
config = require(path)
}
compiler = webpack(config)
}
if (!webpackDev.publicPath) {
if (~Object.keys(compiler).indexOf('compilers')) {
throw new Error('[fastify-webpack-hmr]: You must specify webpackDev.publicPath option in multi compiler mode.')
}
const { publicPath } = compiler.options.output
if (!publicPath) {
throw new Error('[fastify-webpack-hmr]: publicPath must be set on `dev` options, or in a compiler\'s `output` configuration.')
}
webpackDev.publicPath = publicPath
}
await instance.register(require('middie'))
const dev = webpackDevMiddleware(compiler, webpackDev)
instance.use(dev)
let hot = null
if (webpackHot) {
hot = webpackHotMiddleware(compiler, webpackHot)
instance.use(hot)
}
instance
.decorate('webpack', {
compiler,
dev,
hot
})
.addHook('onClose', (instance, next) => {
instance.webpack.dev.close(() => next)
})
}
module.exports = fp(fastifyWebpack, {
fastify: '>=3.x',
name: 'fastify-webpack'
})