A script that combines a folder of SVG files into a single sprites file and generates type definitions for safe usage.

Overview

remix-sprites-example

A script that combines a folder of .svg files into a single sprites.svg file and type definitions for safe usage.

Technical Overview

Compilation Script

Source: scripts/sprites.ts

Here's the basic overview of the compilation script.

  1. Scan the input folder for .svg files.
  2. For Each .svg:
    1. Generate an id based on the path
    2. Parse the file contents in a virtual DOM
    3. Replace the <svg> element in the file with a <symbol> element, copying attributes and children.
    4. Add the generated id to the new symbol element.
  3. Wrap each new <symbol> element in a parent <svg> and output the outerHTML to the configured path.
  4. Generate the TypeScript types and output to the configured path.

Sprite Component

Source: app/Sprite.tsx

This is a relatively boring React component that just spits out HTML like the following:

<svg>
  <use href="sprites.svg#outline:academic-cap"></use>
</svg>

This component is not involved with the compilation process. However, this component is enhanced by the types generated from the script.

import type { SpriteProps } from "~/SpriteProps";

Preloading the Sprites

Source: app/root.tsx

If the loading speed of the sprites is important to you, export a preload link using Remix's Links function. This hints to the browser that the file needs to be loaded soon.

import type { LinksFunction } from "@remix-run/node";
import spriteSrc from "~/sprites.svg";

export const links: LinksFunction = () => {
  return [
    {
      rel: "preload",
      href: spriteSrc,
      as: "image",
    },
  ];
};

Example

Input Files

sprites
├── outline
│   ├── academic-cap.svg
│   ├── adjustments.svg
│   ├── annotation.svg
│   └── archive.svg
└── solid
    ├── academic-cap.svg
    ├── adjustments.svg
    ├── annotation.svg
    └── archive.svg

Sprites Output (truncated for clarity)

<svg>
  <symbol id="outline:academic-cap">...</symbol>
  <symbol id="outline:adjustments">...</symbol>
  <symbol id="outline:annotation">...</symbol>
  <symbol id="outline:archive">...</symbol>
  <symbol id="solid:academic-cap">...</symbol>
  <symbol id="solid:adjustments">...</symbol>
  <symbol id="solid:annotation">...</symbol>
  <symbol id="solid:archive">...</symbol>
</svg>

TypeScript Output

export const spriteNames = [
  "outline:academic-cap",
  "outline:adjustments",
  "outline:annotation",
  "outline:archive",
  "solid:academic-cap",
  "solid:adjustments",
  "solid:annotation",
  "solid:archive",
] as const;
type SpriteName = typeof spriteNames[number];
export type SpriteProps = {
  name: SpriteName;
} & JSX.IntrinsicElements["svg"];

Usage

import Sprite from "~/Sprite";

export default function Example() {
  return (
    <Sprite name="outline:academic-cap" className="w-5 h-5 text-blue-500" />
  );
}

Running the Demo

  1. Clone this repository.
  2. Compile the sprites by running npm run build:sprites
  3. Run npm run dev from your terminal.
  4. Open your browser to http://localhost:3000 and view the index

Potential Improvements

  • Automatically regenerate the sprite when the input folder changes for a better development experience.
  • Gracefully handle parsing errors if the input folder contains a malformed SVG.
  • Test with a wider variety of SVGs to ensure it actually works well 😅

Acknowledgements

  • Ryan Florence sparked this idea in response to a Discord message about the best way to handle icons.
  • Icons within the sprites folder were downloaded from the heroicons repository under the MIT License and are Copyright (c) 2020 Refactoring UI Inc.
You might also like...

Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 3, 2022

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

Zero runtime type-safe CSS in the same file as components

macaron comptime-css is now called macaron! macaron is a zero-runtime and type-safe CSS-in-JS library made with performance in mind Powered by vanilla

Jan 4, 2023

🍎Transform an SVG icon into multiple themes, and generate React icons,Vue icons,svg icons

🍎Transform an SVG icon into multiple themes, and generate React icons,Vue icons,svg icons

IconPark English | 简体中文 Introduction IconPark gives access to more than 2000 high-quality icons, and introduces an interface for customizing your icon

Jan 5, 2023

A Javascript library to export svg charts from the DOM and download them as an SVG file, PDF, or raster image (JPEG, PNG) format. Can be done all in client-side.

svg-exportJS An easy-to-use client-side Javascript library to export SVG graphics from web pages and download them as an SVG file, PDF, or raster imag

Oct 5, 2022

NoExGen is a node.js express application generator with modern folder structure, namespace/project mapping and much more! It contains preconfigured Settings and Routing files, ready to be used in any project.

Installation $ npm install -g noexgen Quick Start You can use Node Package Execution to create your node-express application as shown below: Create th

Oct 8, 2022

Script to fetch all NFT owners using moralis API. This script output is a data.txt file containing all owner addresses of a given NFT and their balances.

Script to fetch all NFT owners using moralis API. This script output is a data.txt file containing all owner addresses of a given NFT and their balances.

🔎 Moralis NFT Snapshot Moralis NFT API will only return 500 itens at a time when its is called. For that reason, a simple logic is needed to fetch al

Jun 23, 2022

Landscape Generator is An open Source web application that generates landscape drawings randomly, then gives you the ability to edit it and export it as SVG or PNG.

Landscape Generator is An open Source web application that generates landscape drawings randomly, then gives you the ability to edit it and export it as SVG or PNG.

Landscape Generator ## About Landscape Generator is An open Source web application that generates landscape drawings randomly, then gives you the abil

Apr 15, 2022

This Photoshop script exports all top-level layers and groups to cropped PNG and JPEG files and creates a file usable in Tumult Hype 4 based on your Photoshop document.

This Photoshop script exports all top-level layers and groups to cropped PNG and JPEG files and creates a file usable in Tumult Hype 4 based on your Photoshop document.

Export To Hype (Photoshop Edition) This Photoshop script exports all top-level layers and groups to cropped PNG and JPEG files and creates a file usab

Nov 9, 2022
Owner
Nicolas Kleiderer
Nicolas Kleiderer
A generative engine that takes various png layers on a sprite sheet format, combines them and then converts them into a .gif file

Welcome to the Generative GIF Engine v2.0.4 ?? [8 minute read] This python and node app generates layered-based gifs to create NFT gif art! It is fast

Jalagar 112 Jan 2, 2023
A generative engine that takes various png layers on a sprite sheet format, combines them and then converts them into a .gif file

Welcome to the Generative Animated Engine v3.0.1 ?? [8 minute read] This repo used to be called jalagar/Generative_Gif_Engine but because it now suppo

Jalagar 47 May 24, 2022
Node module for synchronously and recursively merging multiple folders or collections of files into one folder.

merge-dirs Node module for synchronously and recursively merging multiple folders or collections of files into one folder. Install yarn add @nooooooom

不见月 2 Mar 20, 2022
Organizes all your files from from a folder into different section automatically.

File System Organizer Global command line application Organizes all your files from from a folder into different section automatically. Functionality

KAJALIYA CHARCHIL 4 Jun 15, 2022
Generate type definitions compatible with @kintone/rest-api-client

kintone-form-model-generator Generate type definitions compatible with @kintone/rest-api-client Prerequirements Node.js (>=12) Install # Install npm i

Yuuki Takahashi 5 Dec 15, 2022
TypeScript type definitions for Bun's JavaScript runtime APIs

Bun TypeScript type definitions These are the type definitions for Bun's JavaScript runtime APIs. Installation Install the bun-types npm package: # ya

Oven 73 Dec 16, 2022
100% type-safe query builder for node-postgres :: Generated types, call any function, tree-shakable, implicit type casts, and more

⚠️ This library is currently in alpha. Contributors wanted! tusken Postgres client from a galaxy far, far away. your database is the source-of-truth f

alloc 54 Dec 29, 2022
Opinionated collection of TypeScript definitions and utilities for Deno and Deno Deploy. With complete types for Deno/NPM/TS config files, constructed from official JSON schemas.

Schemas Note: You can also import any type from the default module, ./mod.ts deno.json import { type DenoJson } from "https://deno.land/x/[email protected]

deno911 2 Oct 12, 2022
Serve file server with single zip file as file system in Deno.

zipland Serve file server with one-single zip file in Deno. Support zip just zip32 with deflated or uncompressed serving plaintext deflate Examples Yo

Yongwook Choi 18 Nov 2, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022