Last active
March 11, 2024 11:25
-
-
Save david-plugge/32e2b63f200424d724e83a4159930dbb to your computer and use it in GitHub Desktop.
Lucide svelte optimizer vite plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function lucideSvelteImportOptimizer(): Plugin { | |
return { | |
name: 'vite-plugin-lucide-svelte-optimizer', | |
transform(code, id) { | |
const ms = new MagicString(code, { filename: id }); | |
ms.replace( | |
/([ \t]*)import\s+\{(.*?)\}\s+from\s+['"]lucide-svelte['"];?/g, | |
(match, whitespace: string, importNames: string) => { | |
const hasSemi = match.endsWith(';'); | |
const imports = importNames.split(',').map((str) => { | |
const [name, alias] = str.split(/\sas\s/, 2).map((i) => i.trim()); | |
const path = name | |
.split('') | |
.map((c, i) => { | |
const code = c.charCodeAt(0); | |
return code >= 65 && code <= 90 ? (i === 0 ? '' : '-') + c.toLowerCase() : c; | |
}) | |
.join(''); | |
return `${whitespace}import ${alias || name} from 'lucide-svelte/icons/${path}'${hasSemi ? ';' : ''}`; | |
}); | |
return imports.join('\n'); | |
} | |
); | |
if (ms.hasChanged()) { | |
return { | |
code: ms.toString(), | |
map: ms.generateMap() | |
}; | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment