Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds
Created February 24, 2022 00:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiebuilds/9eafb955672ac21158d95b15aeffde35 to your computer and use it in GitHub Desktop.
Save jamiebuilds/9eafb955672ac21158d95b15aeffde35 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
const fs = require("fs/promises")
const globby = require("globby")
const makeDir = require("make-dir")
const path = require("path")
const svgo = require("svgo")
const REPO_ROOT = path.join(__dirname, "..")
async function main() {
let icons = await globby("./public/icons/**/*.svg", {
cwd: REPO_ROOT,
absolute: true,
onlyFiles: true,
unique: true,
})
for (let icon of icons) {
let relative = path.relative(path.join(REPO_ROOT, "public/icons"), icon)
let contents = await fs.readFile(icon, "utf-8")
let output = svgo.optimize(contents, {
full: false,
multipass: false,
js2svg: { pretty: true, indent: 2 },
plugins: [
{
name: "symbolize",
type: "full",
fn: (ast) => {
return {
...ast,
children: [
{
type: "comment",
value: " Generated by `npm run gen:icons`, do not modify. ",
},
...ast.children.map((child) => {
if (child.type === "element" && child.name === "svg") {
let { xmlns, ...attributes } = child.attributes
return {
...child,
attributes: { xmlns },
children: [
{
type: "element",
name: "symbol",
attributes: {
...attributes,
id: "magic-icon-use-id",
},
children: child.children,
},
],
}
} else {
return child
}
}),
],
}
},
},
],
}).data
let newPath = path.join(REPO_ROOT, "public/icons-embed", relative)
await makeDir(path.dirname(newPath))
await fs.writeFile(newPath, output)
}
}
main().catch((err) => {
console.error(err)
process.exit(1)
})
export type IconName = string
export type IconVariant = "outline" | "solid"
export interface IconProps {
name: IconName
variant: IconVariant
className?: string
}
export function getIconUrl(variant: IconVariant, name: IconName): string {
return `/icons-embed/${variant}/${name}.svg`
}
export function Icon(props: IconProps) {
return (
<svg width={24} height={24} className={props.className}>
<use
href={`${getIconUrl(props.variant, props.name)}#magic-icon-use-id`}
/>
</svg>
)
}
import { Icon } from "./Icon"
export default function Example() {
return (
<Icon
variant="outline"
name="chevron-down"
className="text-gray-400 hover:text-gray-500"
aria-hidden="true"
/>
)
}
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment