-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmodule.ts
178 lines (165 loc) · 5.6 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
import { pathToFileURL } from 'node:url'
import { isAbsolute } from 'node:path'
import {
addTemplate,
addVitePlugin,
addPluginTemplate,
addWebpackPlugin,
resolveAlias,
defineNuxtModule,
useLogger,
} from '@nuxt/kit'
import { resolve } from 'pathe'
import { hasProtocol, withoutLeadingSlash } from 'ufo'
import {
FontaineTransform,
generateFontFace,
generateFallbackName,
getMetricsForFamily,
readMetrics,
} from 'fontaine'
import { NitroTransformPlugin } from './nitro-plugin'
interface CustomFont {
/** The font family name. This will be used to generate the fallback name and also to load cached metrics, if possible. */
family: string
/** A file or web URL to inspect for font metrics. */
src?: string
/** If you want to customise the overridden name. In most cases it should not be overridden. */
fallbackName?: string
/** If you want to customise the fallbacks on a per-font basis. */
fallbacks?: string[]
/** If you want to customise font directory. Default is Nuxt public directory. */
root?: string
}
export interface ModuleOptions {
/** Set to `false` to disable automatic injection of fallbacks. */
inject: boolean
/** Set to `false` to disable inlining of font-face rules. */
inline: boolean
/** An array of local fonts to display as a fallback. */
fallbacks: string[]
/** Fonts to generate fallback declarations for. This is only necessary if you do not have `@font-face` declarations for them in your CSS. */
fonts: Array<string | CustomFont>
/** If you want to customise directory for all fonts. Default is Nuxt public directory. */
root?: string
}
export default defineNuxtModule<ModuleOptions>({
meta: {
configKey: 'fontMetrics',
name: '@nuxtjs/fontaine',
compatibility: {
nuxt: '>=3.0.0-rc.6 || ^4.0.0',
},
},
defaults: nuxt => ({
inject: true,
inline: nuxt.options.ssr,
fallbacks: ['Segoe UI', 'Roboto', 'Helvetica Neue', 'Arial', 'Noto Sans'],
fonts: [],
}),
async setup(options, nuxt) {
// Skip when preparing
if (nuxt.options._prepare) return
// Allow fully overriding default fallbacks
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((nuxt.options as any).fontMetrics?.fallbacks) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.fallbacks = (nuxt.options as any).fontMetrics?.fallbacks
}
const logger = useLogger('@nuxtjs/fontaine')
const css = (async () => {
let css = ''
for (const font of options.fonts) {
const {
family,
src,
fallbackName,
fallbacks,
root: fontRoot,
} = typeof font === 'string' ? ({ family: font } as CustomFont) : font
let metrics = await getMetricsForFamily(family)
if (!metrics && src && !hasProtocol(src)) {
const file = resolve(
nuxt.options.srcDir,
fontRoot ?? options.root ?? nuxt.options.dir.public,
src,
)
metrics = await readMetrics(pathToFileURL(file))
}
if (!metrics) {
logger.warn('Could not find metrics for font', family)
continue
}
for (const font of fallbacks || options.fallbacks) {
css += generateFontFace(metrics, {
name: fallbackName || generateFallbackName(family),
font,
metrics: (await getMetricsForFamily(font))!,
})
}
}
return css
})()
const cssContext = { value: '' }
if (options.inject) {
const resolvePath = (id: string) => {
if (hasProtocol(id)) return id
if (isAbsolute(id))
return pathToFileURL(resolve(nuxt.options.srcDir, nuxt.options.dir.public, withoutLeadingSlash(id)))
return pathToFileURL(resolveAlias(id))
}
const transformOptions = {
fallbacks: options.fallbacks,
resolvePath,
css: cssContext,
skipFontFaceGeneration: (fallbackName: string) => {
return (
options.inline
&& options.fonts.some((font) => {
const previouslyGeneratedFallbackName
= typeof font === 'string'
? generateFallbackName(font)
: font.fallbackName || generateFallbackName(font.family)
return previouslyGeneratedFallbackName === fallbackName
})
)
},
sourcemap: !!nuxt.options.sourcemap.client,
}
addVitePlugin(FontaineTransform.vite(transformOptions), { server: false })
addWebpackPlugin(FontaineTransform.webpack(transformOptions), { server: false })
nuxt.hook('nitro:config', async (config) => {
const plugins = await config.rollupConfig!.plugins
if (!plugins || !Array.isArray(plugins)) return
plugins.push(
NitroTransformPlugin({
sourcemap: true,
cssContext,
}),
)
})
}
if (options.inline) {
addPluginTemplate({
filename: 'font-fallback-inlining-plugin.server.ts',
getContents: async () =>
[
`import { defineNuxtPlugin, useHead } from '#imports'`,
`const css = \`${(await css).replace(/\s+/g, ' ')}\``,
`export default defineNuxtPlugin(() => { useHead({ style: [{ innerHTML: css ${
!nuxt.options.dev && options.inject ? '+ __INLINED_CSS__ ' : ''
}}] }) })`,
].join('\n'),
mode: 'server',
})
}
else {
addTemplate({
filename: 'font-fallbacks.css',
write: true,
getContents: () => css,
})
nuxt.options.css.push('#build/font-fallbacks.css')
}
},
})