-
-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathdevtools.ts
More file actions
80 lines (74 loc) · 2.71 KB
/
devtools.ts
File metadata and controls
80 lines (74 loc) · 2.71 KB
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
import { existsSync } from 'node:fs'
import type { Nuxt } from 'nuxt/schema'
import type { Resolver } from '@nuxt/kit'
import { useNuxt } from '@nuxt/kit'
import { extendServerRpc, onDevToolsInitialized } from '@nuxt/devtools-kit'
import type { ModuleOptions } from '../module'
import type { ClientFunctions, ServerFunctions } from '../rpc-types'
const DEVTOOLS_UI_ROUTE = '/__nuxt-og-image'
const DEVTOOLS_UI_LOCAL_PORT = 3030
export function setupDevToolsUI(options: ModuleOptions, resolve: Resolver['resolve'], nuxt: Nuxt = useNuxt()) {
const clientPath = resolve('./client')
const isProductionBuild = existsSync(clientPath)
// Serve production-built client (used when package is published)
if (isProductionBuild) {
nuxt.hook('vite:serverCreated', async (server) => {
const sirv = await import('sirv').then(r => r.default || r)
server.middlewares.use(
DEVTOOLS_UI_ROUTE,
sirv(clientPath, { dev: true, single: true }),
)
})
}
// In local development, start a separate Nuxt Server and proxy to serve the client
else {
nuxt.hook('vite:extendConfig', (config) => {
config.server = config.server || {}
config.server.proxy = config.server.proxy || {}
config.server.proxy[DEVTOOLS_UI_ROUTE] = {
target: `http://localhost:${DEVTOOLS_UI_LOCAL_PORT}${DEVTOOLS_UI_ROUTE}`,
changeOrigin: true,
followRedirects: true,
rewrite: path => path.replace(DEVTOOLS_UI_ROUTE, ''),
}
})
}
// wait for DevTools to be initialized
onDevToolsInitialized(async () => {
const rpc = extendServerRpc<ClientFunctions, ServerFunctions>('nuxt-og-image', {})
nuxt.hook('builder:watch', (e, path) => {
// needs to be for a page change
if ((e === 'change' || e.includes('link')) && path.startsWith('pages')) {
rpc.broadcast.refreshRouteData(path) // client needs to figure it if it's for the page we're on
.catch(() => {}) // ignore errors
}
if (options.componentDirs.some(dir => path.includes(dir))) {
if (e === 'change') {
rpc.broadcast.refresh()
.catch(() => {})
}
else {
rpc.broadcast.refreshGlobalData().catch(() => {
})
}
}
})
// call client RPC functions
// since it might have multiple clients connected, we use `broadcast` to call all of them
})
nuxt.hook('devtools:customTabs', (tabs) => {
tabs.push({
// unique identifier
name: 'nuxt-og-image',
// title to display in the tab
title: 'OG Image',
// any icon from Iconify, or a URL to an image
icon: 'carbon:image-search',
// iframe view
view: {
type: 'iframe',
src: DEVTOOLS_UI_ROUTE,
},
})
})
}