Last active
April 6, 2022 08:43
-
-
Save lukaskoeller/66be125d2ff9ca4dfdda31a2de727a89 to your computer and use it in GitHub Desktop.
Creates a map of all icons within a directory and puts them in a single file with consisting naming
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
#!/usr/bin/env node | |
// Icon Map Build Script | |
const { readdirSync, writeFileSync } = require('fs'); | |
const ICON_SOURCE_FOLDER = './'; | |
const ICON_MAP_FILE_DEST_FOLDER = './iconUrlMap.ts'; | |
// Prefix to escape syntax error by icon names that start with a digit or equal "react". | |
const prefix = 'svg'; | |
const suffix = 'Url'; | |
// Transform file name to svg<name>Url using Pascal Case | |
const isSVG = (file) => /.svg$/.test(file); | |
const removeExtension = (file) => file.split('.')[0]; | |
const toPascalCase = (string) => prefix + string.replace(/(^\w|-\w|_\w)/g, | |
(str) => str.replace(/[-_]/, '').toUpperCase()) + suffix; | |
// Getting all the icons | |
const icons = readdirSync(ICON_SOURCE_FOLDER) | |
.filter(isSVG) | |
.map(removeExtension); | |
// Generate code for icon map file | |
const iconMapContent = [ | |
`/** | |
* Do not edit directly | |
* Generated on ${new Date()} | |
* | |
* To regenerate, run 'npx https://gist.github.com/lukaskoeller/66be125d2ff9ca4dfdda31a2de727a89' | |
* More on static assets url imports, see https://vitejs.dev/guide/features.html#static-assets | |
*/ | |
`, | |
icons | |
.map( | |
(icon) => `import ${toPascalCase(icon)} from './${icon}.svg?url';`, | |
) | |
.join('\n'), | |
'', | |
'export {', | |
icons.map((icon) => ` ${toPascalCase(icon)},`).join('\n'), | |
'};', | |
'' | |
].join('\n'); | |
// Write icon map file | |
writeFileSync(ICON_MAP_FILE_DEST_FOLDER, iconMapContent); |
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
{ | |
"name": "build-icon-url-map-ts", | |
"version": "1.0.1", | |
"bin": "./index.js" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment