Skip to content

Commit

Permalink
feat: added inject parameter to specify the svgDom insertion position,
Browse files Browse the repository at this point in the history
…close #36
  • Loading branch information
shisan committed Jan 27, 2022
1 parent 465e537 commit e44ce2c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
14 changes: 12 additions & 2 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -29,6 +29,7 @@ export function createSvgIconsPlugin(opt: ViteSvgIconsPlugin): Plugin {
const options = {
svgoOptions: true,
symbolId: 'icon-[dir]-[name]',
inject: 'body-last' as const,
...opt,
}

Expand Down Expand Up @@ -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);
Expand All @@ -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
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/typing.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -17,6 +19,12 @@ export interface ViteSvgIconsPlugin {
* @default: icon-[dir]-[name]
*/
symbolId?: string

/**
* icon format
* @default: body-last
*/
inject?: DomInject
}

export interface FileStats {
Expand Down

0 comments on commit e44ce2c

Please sign in to comment.