-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathmodule.ts
227 lines (199 loc) · 7.58 KB
/
module.ts
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
import fs from 'node:fs/promises'
import { defineNuxtModule, addPlugin, addServerHandler, hasNuxtModule, createResolver, addComponent, logger, updateTemplates, resolvePath as nuxtResolvePath, addVitePlugin } from '@nuxt/kit'
import { addCustomTab } from '@nuxt/devtools-kit'
import { resolvePath } from 'mlly'
import type { ViteDevServer } from 'vite'
import type { Nuxt } from '@nuxt/schema'
import { schema } from './schema'
import type { ModuleOptions, NuxtIconRuntimeOptions } from './types'
import { unocssIntegration } from './integrations/unocss'
import { registerServerBundle } from './bundle-server'
import { registerClientBundle } from './bundle-client'
import { NuxtIconModuleContext } from './context'
import { getCollectionPath } from './collections'
export type { ModuleOptions, NuxtIconRuntimeOptions as RuntimeOptions }
export default defineNuxtModule<ModuleOptions>({
meta: {
name: '@nuxt/icon',
configKey: 'icon',
compatibility: {
nuxt: '>=3.0.0',
},
},
defaults: {
// Module options
componentName: 'Icon',
serverBundle: 'auto',
serverKnownCssClasses: [],
clientBundle: {
icons: [],
},
// Runtime options
provider: schema['provider'].$default,
class: schema['class'].$default,
size: schema['size'].$default,
aliases: schema['aliases'].$default,
iconifyApiEndpoint: schema['iconifyApiEndpoint'].$default,
localApiEndpoint: schema['localApiEndpoint'].$default,
fallbackToApi: schema['fallbackToApi'].$default,
cssSelectorPrefix: schema['cssSelectorPrefix'].$default,
cssWherePseudo: schema['cssWherePseudo'].$default,
cssLayer: schema['cssLayer'].$default,
mode: schema['mode'].$default,
attrs: schema['attrs'].$default,
collections: schema['collections'].$default,
fetchTimeout: schema['fetchTimeout'].$default,
},
async setup(options, nuxt) {
const resolver = createResolver(import.meta.url)
// @ts-expect-error `customize` is not allowed in module options
if (typeof options.customize === 'function') {
throw new TypeError('`customize` callback can\'t not be set in module options, use `app.config.ts` or component props instead.')
}
// Use `server` provider when SSR is disabled or generate mode
if (!options.provider) {
options.provider = (!nuxt.options.ssr || nuxt.options._generate)
? 'iconify'
: 'server'
}
// In some monorepo, `@iconify/vue` might be bundled twice which does not share the loaded data
nuxt.options.vite ||= {}
nuxt.options.vite.resolve ||= {}
nuxt.options.vite.resolve.dedupe ||= []
nuxt.options.vite.resolve.dedupe.push('@iconify/vue')
// Create context
const ctx = new NuxtIconModuleContext(nuxt, options)
addPlugin(
resolver.resolve('./runtime/plugin'),
)
addComponent({
name: options.componentName || 'Icon',
global: true,
filePath: await resolver.resolvePath('./runtime/components/index'),
})
addServerHandler({
route: `${options.localApiEndpoint || '/api/_nuxt_icon'}/:collection`,
handler: resolver.resolve('./runtime/server/api'),
})
await setupCustomCollectionsWatcher(options, nuxt, ctx)
// Merge options to app.config
const runtimeOptions = Object.fromEntries(
Object.entries(options)
.filter(([key]) => key in schema),
) as NuxtIconRuntimeOptions
if (!runtimeOptions.collections) {
runtimeOptions.collections = ctx.getRuntimeCollections(runtimeOptions)
}
nuxt.options.appConfig.icon = Object.assign(
nuxt.options.appConfig.icon || {},
runtimeOptions,
{
customCollections: options.customCollections?.map(i => i.prefix),
},
)
// Define types for the app.config compatible with Nuxt Studio
nuxt.hook('schema:extend', (schemas) => {
schemas.push({
appConfig: {
icon: schema,
},
})
})
nuxt.hook('nitro:config', async (nitroConfig) => {
ctx.setNitroPreset(nitroConfig.preset as string)
const bundle = await ctx.resolveServerBundle()
if (bundle.remote || !bundle.externalizeIconsJson)
return
logger.warn('Nuxt Icon\'s `serverBundle.externalizeIconsJson` is en experimental feature, it would require your production Node.js server able to import JSON modules.')
const collections = bundle.collections
.filter(collection => typeof collection === 'string')
.map(collection => getCollectionPath(collection))
const resolvedPaths = await Promise.all(
collections.map(collection => resolvePath(collection, {
url: nuxt.options.rootDir,
})))
// Trace iconify-json modules
nitroConfig.externals ||= {}
nitroConfig.externals.traceInclude ||= []
nitroConfig.externals.traceInclude.push(...resolvedPaths)
// Add rollup plugin to externalize iconify-json
nitroConfig.rollupConfig ||= {}
nitroConfig.rollupConfig.plugins ||= [];
(nitroConfig.rollupConfig.plugins as unknown[]).unshift({
name: '@nuxt/icon:rollup',
resolveId(id: string) {
if (id.match(/(?:[\\/]|^)(@iconify-json[\\/]|@iconify[\\/]json)/)) {
return { id, external: true }
}
},
})
})
registerServerBundle(ctx)
registerClientBundle(ctx)
// Devtools
addCustomTab({
name: 'icones',
title: 'Icônes',
icon: 'https://icones.js.org/favicon.svg',
view: {
type: 'iframe',
src: 'https://icones.js.org',
},
})
// Server-only runtime config for known CSS selectors
options.serverKnownCssClasses ||= []
const serverKnownCssClasses = options.serverKnownCssClasses || []
nuxt.options.runtimeConfig.icon = {
serverKnownCssClasses,
}
nuxt.hook('nitro:init', async (_nitro) => {
_nitro.options.runtimeConfig.icon = {
serverKnownCssClasses,
}
})
if (hasNuxtModule('@unocss/nuxt'))
unocssIntegration(nuxt, options)
await nuxt.callHook('icon:serverKnownCssClasses', serverKnownCssClasses)
},
})
async function setupCustomCollectionsWatcher(options: ModuleOptions, nuxt: Nuxt, ctx: NuxtIconModuleContext) {
if (!options.customCollections?.length)
return
let viteDevServer: ViteDevServer
const collectionDirs = await Promise.all(options.customCollections.map(x => nuxtResolvePath(x.dir)))
if (options.clientBundle?.includeCustomCollections) {
addVitePlugin({
name: 'nuxt-icon/client-bundle-updater',
apply: 'serve',
configureServer(server) {
viteDevServer = server
},
})
}
nuxt.hook('builder:watch', async (event, path) => {
const resolvedPath = await nuxtResolvePath(path)
if (ctx.scanner) {
const matched = ctx.scanner.isFileMatch(path)
console.log({ path, matched })
ctx.scanner.extractFromCode(
await fs.readFile(resolvedPath, 'utf-8').catch(() => ''),
ctx.scannedIcons,
)
}
if (collectionDirs.some(cd => resolvedPath.startsWith(cd))) {
await ctx.loadCustomCollection(true) // Force re-read icons from fs
// Update client and server bundles
await updateTemplates({
filter: template => template.filename.startsWith('nuxt-icon-'),
})
if (viteDevServer) {
// Invalidate client bundle in vite dev server cache
const nuxtIconClientBundleModule = await viteDevServer.moduleGraph.getModuleByUrl('/.nuxt/nuxt-icon-client-bundle.mjs')
if (nuxtIconClientBundleModule) {
viteDevServer.moduleGraph.invalidateModule(nuxtIconClientBundleModule)
await viteDevServer.reloadModule(nuxtIconClientBundleModule)
}
}
}
})
}