README
Typed SVG
Typed SVG is a webpack plugin to generate types for SVG sprites.
Install
yarn add typed-svg
# or npm
npm install typed-svg
Setup
This plugin is intended to be used in conjunction with file-loader.
// webpack.config.js
import { TypedSVGWebpackPlugin } from "typed-svg";
{
plugins: [
new TypedSVGWebpackPlugin(),
]
}
Usage
This plugin will compile a type for any svg that ends with the name .sprite.svg While this example is done in React, there's nothing React specific to this plugin.
// Icon.tsx
import React from "react";
import spritePath, { Symbols } from "./sprite.svg";
export interface IconProps extends React.SVGProps<SVGSVGElement> {
name: Symbols;
}
export default (props: IconProps) => (
<svg>
<use xlinkHref={`${spritePath}#${props.name}`} />
</svg>
);
<!-- sprite.svg -->
<svg xmlns="http://www.w3.org/2000/svg">
<defs>
<symbol id="shopping-cart">
<path />
</symbol>
<symbol id="search">
<path />
</symbol>
</defs>
</svg>
Given the files above a spite.svg.d.ts file will be generated when webpack is run. This file will be placed next to sprite.svg.
// spite.svg.d.ts
// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
declare const _default: string;
export default _default;
export const symbol: "shopping-cart" | "search";
Why
Shipping SVGs as React components is simple, but can dramatically bloat the size of JavaScript bundles. This plugin aims to make using the browsers <svg>
and <use>
tags safer. Without types it's all to easy to have a mismatch between the id used in your <use>
tag and the id of the SVG symbol.