From e44ce2cc825a3b9fcdc944528cfd0785b1f39ac7 Mon Sep 17 00:00:00 2001 From: shisan Date: Fri, 28 Jan 2022 00:51:22 +0800 Subject: [PATCH] feat: added inject parameter to specify the svgDom insertion position, close #36 --- packages/core/src/index.ts | 14 ++++++++++++-- packages/core/src/typing.ts | 8 ++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index daccfe2..77434d7 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,6 +1,6 @@ import type { Plugin } from 'vite' import type { OptimizedSvg, OptimizeOptions } from 'svgo' -import type { ViteSvgIconsPlugin, FileStats } from './typing' +import type { ViteSvgIconsPlugin, FileStats, DomInject } from './typing' import fg from 'fast-glob' import getEtag from 'etag' import cors from 'cors' @@ -29,6 +29,7 @@ export function createSvgIconsPlugin(opt: ViteSvgIconsPlugin): Plugin { const options = { svgoOptions: true, symbolId: 'icon-[dir]-[name]', + inject: 'body-last' as const, ...opt, } @@ -136,7 +137,7 @@ export async function createModuleCode( svgDom.setAttribute('xmlns:link','${XMLNS_LINK}'); } svgDom.innerHTML = ${JSON.stringify(html)}; - body.insertBefore(svgDom, body.firstChild); + ${domInject(options.inject)} } if(document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', loadSvg); @@ -151,6 +152,15 @@ export async function createModuleCode( } } +function domInject(inject: DomInject = 'body-last') { + switch (inject) { + case 'body-first': + return 'body.insertBefore(svgDom, body.firstChild);' + default: + return 'body.insertBefore(svgDom, body.lastChild);' + } +} + /** * Preload all icons in advance * @param cache diff --git a/packages/core/src/typing.ts b/packages/core/src/typing.ts index adb21b5..f0028e3 100644 --- a/packages/core/src/typing.ts +++ b/packages/core/src/typing.ts @@ -1,5 +1,7 @@ import type { OptimizeOptions } from 'svgo' +export type DomInject = 'body-first' | 'body-last' + export interface ViteSvgIconsPlugin { /** * icons folder, all svg files in it will be converted to svg sprite. @@ -17,6 +19,12 @@ export interface ViteSvgIconsPlugin { * @default: icon-[dir]-[name] */ symbolId?: string + + /** + * icon format + * @default: body-last + */ + inject?: DomInject } export interface FileStats {