-
Notifications
You must be signed in to change notification settings - Fork 12
/
plugin.js
executable file
·66 lines (57 loc) · 1.41 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
61
62
63
64
65
66
exports.register = async function (server, _config) {
// Apply defaults
const config = {
dev: process.env.NODE_ENV !== 'production',
rootDir: process.cwd(),
edge: false,
baseURL: null,
route: {},
routeMethod: '*',
..._config
}
// Requre Nuxt
const { loadNuxt, getBuilder } = tryRequire('nuxt-edge') || tryRequire('nuxt')
if (!loadNuxt) {
throw new Error('Ensure nuxt or nuxt-edge >= 2.12 is instaled')
}
// Initialize nuxt
const nuxt = await loadNuxt({
rootDir: config.rootDir,
configOverrides: config.overrides,
for: config.dev ? 'dev' : 'start'
})
// Expose nuxt
server.expose('nuxt', nuxt)
// Route handler
server.route({
method: config.routeMethod,
path: config.baseURL ? `/${config.baseURL}/{path*}`.replace('//', '/') : '/{path*}',
config: {
id: 'nuxt.render',
auth: false,
...config.route
},
handler (request, h) {
const { req, res } = request.raw
req.hapi = request
res.hapi = h
nuxt.render(req, res)
// https://hapijs.com/api#h.abandon
return h.abandon
}
})
// Development mode
if (config.dev) {
const builder = await getBuilder(nuxt)
server.expose('builder', builder)
builder.build().catch(console.error)
}
}
function tryRequire (pkg) {
try {
return require(pkg)
} catch (err) {
}
}
exports.name = 'nuxt'
exports.pkg = require('../package.json')