diff --git a/packages/preset-web-fonts/README.md b/packages/preset-web-fonts/README.md index 4daf709833..8742fbc536 100644 --- a/packages/preset-web-fonts/README.md +++ b/packages/preset-web-fonts/README.md @@ -75,6 +75,32 @@ Currently supported Providers: PR welcome to add more providers 🙌 +### Custom fetch function + +Use your own function to fetch font source. + +```ts +import presetWebFonts from '@unocss/preset-web-fonts' +import presetUno from '@unocss/preset-uno' +import axios from 'axios' +import ProxyAgent from 'proxy-agent' + +Unocss({ + presets: [ + presetUno(), + presetWebFonts({ + // use axios with an https proxy + customFetch: (url: string) => axios.get(url, { httpsAgent: new ProxyAgent('https://localhost:7890') }), + provider: 'google', + fonts: { + sans: 'Roboto', + mono: ['Fira Code', 'Fira Mono:400,700'], + }, + }), + ], +}) +``` + ## Configuration Refer to the [type definition](https://github.com/unocss/unocss/blob/main/packages/preset-web-fonts/src/types.ts#L4) for all configurations available. diff --git a/packages/preset-web-fonts/src/index.ts b/packages/preset-web-fonts/src/index.ts index 2e8395a6dd..1991f0f0fb 100644 --- a/packages/preset-web-fonts/src/index.ts +++ b/packages/preset-web-fonts/src/index.ts @@ -35,6 +35,7 @@ const preset = (options: WebFontsOptions = {}): Preset => { extendTheme = true, inlineImports = true, themeKey = 'fontFamily', + customFetch, } = options const fontObject = Object.fromEntries( @@ -48,14 +49,15 @@ const preset = (options: WebFontsOptions = {}): Preset => { async function importUrl(url: string) { if (inlineImports) { if (!importCache[url]) { - const { $fetch } = await import('ohmyfetch') - importCache[url] = $fetch(url, { headers: {}, retry: 3 }) - .catch((e) => { - console.error('Failed to fetch web fonts') - console.error(e) - if (typeof process !== 'undefined' && process.env.CI) - throw e - }) + const promise = customFetch + ? customFetch(url) + : (await import('ohmyfetch')).$fetch(url, { headers: {}, retry: 3 }) + importCache[url] = promise.catch((e) => { + console.error('Failed to fetch web fonts') + console.error(e) + if (typeof process !== 'undefined' && process.env.CI) + throw e + }) } return await importCache[url] } diff --git a/packages/preset-web-fonts/src/types.ts b/packages/preset-web-fonts/src/types.ts index 38b390dfb2..8b31bac8b3 100644 --- a/packages/preset-web-fonts/src/types.ts +++ b/packages/preset-web-fonts/src/types.ts @@ -42,6 +42,13 @@ export interface WebFontsOptions { * @default true */ inlineImports?: boolean + + /** + * Custom fetch function + * + * @default undefined + */ + customFetch?: (url: string) => Promise } export interface Provider {