diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 009fdc8..121ecc5 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -107,6 +107,34 @@ export function createSvgIconsPlugin(opt: ViteSvgIconsPlugin): Plugin { } }) }, + + async transformIndexHtml(html) { + if (options.inject !== 'index-html') { + return html + } + + const { html: svgHtml } = await createModuleCode( + cache, + svgoOptions as OptimizeOptions, + options, + ) + + return [ + { + injectTo: 'body-prepend', + tag: 'svg', + attrs: { + xmlns: XMLNS, + 'xmlns:xlink': XMLNS_LINK, + id: options.customDomId, + 'aria-hidden': 'true', + style: + 'position: absolute; width: 0; height: 0; pointer-events: none;', + }, + children: svgHtml, + }, + ] + }, } } @@ -151,6 +179,7 @@ export async function createModuleCode( return { code: `${code}\nexport default {}`, idSet: `export default ${JSON.stringify(Array.from(idSet))}`, + html, } } diff --git a/packages/core/src/typing.ts b/packages/core/src/typing.ts index 53e8eef..f84e909 100644 --- a/packages/core/src/typing.ts +++ b/packages/core/src/typing.ts @@ -1,6 +1,6 @@ import type { OptimizeOptions } from 'svgo' -export type DomInject = 'body-first' | 'body-last' +export type DomInject = 'body-first' | 'body-last' | 'index-html' export interface ViteSvgIconsPlugin { /** diff --git a/packages/playground/basic/vite.config.ts b/packages/playground/basic/vite.config.ts index ebd0c0d..d3f5d0c 100644 --- a/packages/playground/basic/vite.config.ts +++ b/packages/playground/basic/vite.config.ts @@ -14,6 +14,7 @@ export default (): UserConfigExport => { // icon symbolId // default symbolId: 'icon-[dir]-[name]', + inject: 'index-html', }), ], }