Skip to content

Commit

Permalink
feat: added emitFile
Browse files Browse the repository at this point in the history
  • Loading branch information
vshepel committed Mar 31, 2024
1 parent dfa7511 commit f8ac8cd
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 18 deletions.
2 changes: 1 addition & 1 deletion example/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
</head>
<body>
<svg class="icon" aria-hidden="true">
<use xlink:href="sprite.svg#star"></use>
<use xlink:href="public/sprite.svg#star"></use>
</svg>
</body>
</html>
6 changes: 5 additions & 1 deletion example/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ export default defineConfig({
plugins: [
ViteSvgSpriteWrapper({
icons: 'svg/*.svg',
outputDir: '',
outputDir: './public',
}),
],
build: {
copyPublicDir: false,
manifest: true,
},
})
41 changes: 25 additions & 16 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { dirname, resolve } from 'node:path'
import { basename, dirname, resolve } from 'node:path'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { cwd } from 'node:process'
import { type PluginOption, type ResolvedConfig, type ViteDevServer, normalizePath } from 'vite'
Expand Down Expand Up @@ -157,12 +157,14 @@ async function generateSvgSprite(options: Required<Options>): Promise<string> {
if (!existsSync(outputDir))
mkdirSync(outputDir, { recursive: true })

const sprite = result.symbol.sprite

writeFileSync(
result.symbol.sprite.path,
result.symbol.sprite.contents.toString('utf8'),
sprite.path,
sprite.contents.toString(),
)

return result.symbol.sprite.path.replace(`${root}/`, '')
return sprite.path.replace(`${root}/`, '')
}

function ViteSvgSpriteWrapper(options: Options = {}): PluginOption {
Expand Down Expand Up @@ -195,12 +197,21 @@ function ViteSvgSpriteWrapper(options: Options = {}): PluginOption {
config = _config
},
enforce: 'pre',
buildStart: {
async handler() {
generateSvgSprite(resolved)
.then(successGeneration)
.catch(failGeneration)
},
async buildStart() {
await generateSvgSprite(resolved)
.then((path) => {
const name = basename(path)
const source = readFileSync(`${root}/${path}`)

this.emitFile({
name,
source,
type: 'asset',
})

successGeneration(path)
})
.catch(failGeneration)
},
},
{
Expand All @@ -210,12 +221,10 @@ function ViteSvgSpriteWrapper(options: Options = {}): PluginOption {
config = _config
},
enforce: 'pre',
buildStart: {
async handler() {
generateSvgSprite(resolved)
.then(successGeneration)
.catch(failGeneration)
},
async buildStart() {
await generateSvgSprite(resolved)
.then(successGeneration)
.catch(failGeneration)
},
config: () => ({ server: { watch: { disableGlobbing: false } } }),
configureServer({ watcher, hot }: ViteDevServer) {
Expand Down

0 comments on commit f8ac8cd

Please sign in to comment.