Skip to content

Instantly share code, notes, and snippets.

@lukaskoeller
Last active April 6, 2022 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukaskoeller/66be125d2ff9ca4dfdda31a2de727a89 to your computer and use it in GitHub Desktop.
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
#!/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);
{
"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