@gitborlando/vite-plugin-nested-assets
v0.1.0
Published
Generate a typed nested asset map from a directory in Vite.
Readme
@gitborlando/vite-plugin-nested-assets
Generate a typed nested asset map from a directory.
The plugin scans static assets under base, creates import statements for each file, and writes an assets.ts file that mirrors the folder structure.
Install
pnpm add -D @gitborlando/vite-plugin-nested-assetsUsage
import vitePluginNestedAssets from '@gitborlando/vite-plugin-nested-assets'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
vitePluginNestedAssets({
base: 'src/view/assets',
}),
],
})With files like this:
src/view/assets/
editor/node/rect.svg
fav-icon/sigma-logo.pngThe plugin generates:
export const Assets = {
editor: {
node: {
rect: editorNodeRect,
},
},
favIcon: {
sigmaLogo: favIconSigmaLogo,
},
} as constThen use it in app code:
import { Assets } from 'src/view/assets/assets'
const rectIcon = Assets.editor.node.rectOptions
interface VitePluginNestedAssetsOptions {
base: string
export?: string
aliases?: Record<string, string | readonly string[]>
include?: string | readonly string[]
output?: string
}base: asset root directory, resolved from Viteconfig.root.export: generated export name. Defaults toAssets.include: glob pattern used to find assets. Defaults to common image formats.output: generated file path. Defaults to${base}/assets.ts.aliases: extra top-level groups generated from specific patterns.
Naming
File and folder names are converted to camel case:
fav-icon/sigma-logo.png -> Assets.favIcon.sigmaLogoIf an asset key conflicts with a directory or another asset key, the file extension is appended:
foo.png
foo/bar.svg
-> Assets.fooPng
-> Assets.foo.barIf generated import variable names conflict, later imports receive a number suffix.
Property names that are not valid TypeScript identifiers are emitted as string keys, so the generated file stays valid TypeScript.
