svg-to-ts

Build amazing svg icon libraries

Usage no npm install needed!

<script type="module">
  import svgToTs from 'https://cdn.skypack.dev/svg-to-ts';
</script>

README

Logo

All Contributors

What is svg-to-ts?

svg-to-ts is a helper tool that converts your SVG icons to TypeScript. svg-to-ts can convert SVGs to either one TypeScript file with exported constants, multiple TypeScript files or compiled JavaScript files with according declaration files. Furthermore, it generates all typings in form of interfaces and types.

The generated output can then be used in combination with a iconregistry to create a tree shakable icon library. (More informations...)

Who is this for?

svg-to-ts is designed for autors of component libraries or icon libraries. Our examples and tutorials are made with Angular, however svg-to-ts can also be used with other frameworks or vanilla TypeScript / JavaScript.

Why you should use svg-to-ts

  • svg-to-ts helps you provide icons in a tree shakable and performant way.
  • You get free step to step guides in form of blog posts, that walk you through the process of creating your own tree shakable icon library
  • svg-to-ts optimizes your SVG icons under the hood
  • svg-to-ts automatically generates types and interfaces for your icons to improve typesafety
  • svg-to-ts was developed based on the experiences of providin an icon library for a large enterprise.
  • offers three different conversion modes ('object', 'constants' and 'files')
  • each method is highly configurable to supports multiple use cases.

Step by step guide on how to create your icon library

We created multiple tutorials to show you how you can use svg-to-ts in the best way. We have two step by step guides. A video course and a blog post. Both cover the same content. Feel free to choose the format you prefer.

Video tutorials

IMAGE ALT TEXT HERE

Writtern tutorial

This blog post guides you through the process of building your own icon library with svg-to-ts. Logo

How to use svg-to-ts

svg-to-ts is a command line tool, it can either be used directly in your terminal or via npm script.

Usage

Binaries

svg-to-ts provides three different binaries.

  • svg-to-ts-object
  • svg-to-ts-constants
  • svg-to-ts-files

You can either run those binaries with npx

npx svg-to-ts svg-to-ts-object

or you can add a new script in your package.json.

"name": "my-icon-library",
"version": "3.4.0",
"scripts": {
  "generate-icons": "svg-to-ts"
}```

Configuration

When executing a binary svg-to-ts automatically applies some defaults. However, you have multiple ways to configure svg-to-ts. To get a list of available options you can either execute the binary of your choice with the --help argument or you can find all the available options for your conversion type here in the docs:

Once you found your configurations you have the following possibilities to configure svg-to-ts:

  • Passing arguments to the binary
  • Adding a configuration object in the package.json
  • Adding a .svg-to-tsrc file (javascript, json , yaml or yml) in the root of your project or a path of you choice.

Passing arguments to the binary

When choosing this option you directly pass the arguments to your binary.

svg-to-ts-files -s './inputfiles/*.svg' --compileSources true --additionalModelOutputPath ./additional

A complete list of the available arguments can be found by using the --help argument.

svg-to-ts-files --help

When you start using svg-to-ts in bigger projects, configuration may get more sophisticated. At this point command line arguments are hard to read.

Configure svg-to-ts over package.json

To configure svg-to-ts over package.json you can add a svg-to-ts key in your package.json and use the config options. Once you run svg-to-ts those configurations will be picked up. The config object can eiter be an object or an array containing multiple configurations.

{
  "name": "my-icon-library",
  "version": "3.4.0",
  "scripts": {
    "generate-icons": "svg-to-ts"
  },
  "svg-to-ts": {
    "srcFiles": ["./projects/dinosaur-icons/icons/**/*.svg"],
    "outputDirectory": "./projects/dinosaur-icons/icons",
    "interfaceName": "DinosaurIcon",
    "typeName": "dinosaurIcon",
    "prefix": "dinosaurIcon",
    "svgoConfig": {
      "plugins": ["cleanupAttrs"]
    },
    "fileName": "dinosaur-icon.model",
    "additionalModelFile": "./projects/dinosaur-icons/src/lib",
    "compileSources": true
  }
}

Configuration file

To configure svg-to-ts over a .rc file you can add a .svg-to-tsrc file in the root of your project and use the config options. Once you run svg-to-ts those configurations will be picked up.

{
  "srcFiles": ["./projects/dinosaur-icons/icons/**/*.svg"],
  "outputDirectory": "./projects/dinosaur-icons/icons",
  "interfaceName": "DinosaurIcon",
  "typeName": "dinosaurIcon",
  "prefix": "dinosaurIcon",
  "fileName": "dinosaur-icon.model",
  "svgoConfig": {
    "plugins": ["cleanupAttrs"]
  },
  "additionalModelFile": "./projects/dinosaur-icons/src/lib",
  "compileSources": true
}

An alternative for bigger projects is to use a JavaScript-based configuration file. The main advantage here is there you can create dynamic configurations, but also use plain-old JavaScript objects, allowing you to add comments, etc. This is useful for more complex configurations where comments can clarify why options are defined in a certain way.

JS configurations must be defined as a CommonJS module.

Here's an example:

const svgToTsConfig = {
  srcFiles: ['./libs/web-icons/icons/**/*.svg'],
  outputDirectory: './libs/web-icons/src/lib',
  interfaceName: 'MyIcon',
  typeName: 'MyIconName',
  generateType: true,
  modelFileName: 'whatever-icon.model',
  additionalModelFile: './libs/web-icons/src/lib',
  iconsFolderName: 'generated',
  delimiter: 'SNAKE',
  barrelFileName: 'generated-icons-barrel',
  svgoConfig: {
    plugins: ['cleanupAttrs']
  },
  compileSources: false
};

module.exports = svgToTsConfig;

Using a custom path

In case you want to put your configuration under a custom path, you can use the --config property to specify a path your configuration. For example svg-to-ts --config ./myconfig.json.

ConversionTypes

svg-to-ts offers three different kinds of conversion types; Converting your icons to a single object, converting your icons to constants or converting your icons to single files. Each approach is designed to solve a specific kind of problem. You can switch between approaches by passing conversionType property (object, constants or files).

1. Converting to a single object (conversionType==='object')

In this scenario the SVG icons are converted to a single object. It's an approach that is suitable if your icon registry accepts an object with the filename as key and the svg data as key.

Available options:

--version type default description
fileName string my-icons file name of the generated file
delimiter CAMEL, KEBAB, SNAKE, UPPER CAMEL delimiter which is used to generate the types and name properties
svgoConfig null or config object check help command - to large to display by default we search for a svgo.config.js file in the root or an inline configuration object
srcFiles string "/*.svg" input files matching the given filename pattern
outputDirectory string "./dist" name of the output directory
objectName string default - export name of the exported const - if nothing is set - default export will be used
verbose boolean false defines if the log should contain additional information. Can be useful for debugging

Example usage

Let's say we have the following four svg files in a inputfiles folder.

  • expressionless.svg
  • full.svg
  • laughing.svg
  • smiling-face.svg

We can now run svg-to-ts-object -s ./inputfiles -o ./dist and we end up with the following file in our dist folder.

Sample output

export default {
  expressionLess: '<svg xmlns="http://ww...',
  full: '<svg xmlns="http://...',
  laughing: '<svg xmlns="http://ww...',
  smilingFace: '<svg xmlns="http://www....'
};

2. Multiple constants - Treeshakable and typesafe with one file (conversionType==='constants')

This approach converts your svg icons into multiple constants in the same file so that they can be used in combination with an icon registry. It furthermore also generates all necssary types. We wrote a step to step guide that explains this approach further and helps you create an icon library with this approach. Find out more in this blogpost

Output scenario one Only the icons included in the consuming SPA also end up in the final bundle of the SPA.

Available options:

--version type default description
typeName string myIcons name of the generated type
generateType boolean false prevent generating enumeration type
generateTypeObject boolean false generate type object
generateEnum boolean false generate enum object
prefix string myIcon prefix for the generated svg constants
interfaceName string MyIcon name for the generated interface
fileName string my-icons file name of the generated file
enumName string MyIcons name for the generated enum
delimiter CAMEL, KEBAB, SNAKE, UPPER SNAKE delimiter which is used to generate the types and name properties
svgoConfig string or config object check help command - to large to display a path to your svgoConfiguration JSON file or an inline configuration object
srcFiles string "/*.svg" input files matching the given filename pattern
outputDirectory string "./dist" name of the output directory
exportCompleteIconSet boolean true exports a complete icon set
completeIconSetName string completeIconSet Default name of the exported variable
verbose boolean false defines if the log should contain additional information. Can be useful for debugging

Example usage

Let's say we have the following four svg files in a inputfiles folder.

  • expressionless.svg
  • full.svg
  • laughing.svg
  • smiling-face.svg

We can now run svg-to-ts-constants -s ./inputfiles -o ./dist and we end up with the following file in our dist folder.

Sample ouput

export const myIconExpressionLess: MyIcon = {
  name: 'expression_less',
  data: `<svg xmlns="http://...`
};
export const myIconFull: MyIcon = {
  name: 'full',
  data: `<svg xmlns="http://www...`
};
export const myIconLaughing: MyIcon = {
  name: 'laughing',
  data: `<svg xmlns="http://www.w...`
};
export const myIconSmilingFace: MyIcon = {
  name: 'smiling_face',
  data: `<svg xmlns="http://www.w3...`
};
/* ⚠️ Do not edit this file - this file is generated by svg-to-ts*/

export type myIcons = 'expression_less' | 'full' | 'laughing' | 'smiling_face';
export interface MyIcon {
  name: myIcons;
  data: string;
}

3. Tree shakable and optimized for lazy loading (conversionType==='files')

This is the most sophisticated approach and also the approach that doesn't only support tree shaking but also supports code splitting which is especially usefull in scenarios where you are using lazy loading.

Here's a step by step guide on how to create an icon library that is optimized for tree shaking

fully tree shakable Often, having the SVGs in a single file is enough. However, if you are in a more complex environment with bigger business applications, you may want to make the icons even more tree shakable.

In Angular, for example, having all icons in a single file shakes out the icons that are not used. However, icons always end up together in a chunk. The conversionOption = files allows you to configure svg-to-ts that icons are generated in a way that they can even be split to lazy loaded chunks. Means not only the amount of the icons in the chunk gets reduced, but also, where they end up. Means, an icon that is only used in a lazy loaded Angular feature module, will only end up there.

Available options:

--version type default description
barrelFileName string index name of the generated type
typeName string myIcons name of the generated type
generateType boolean false prevent generating enumeration type
generateTypeObject boolean false generate type object
generateEnum boolean false generate enum object
exportCompleteIconSet boolean false Specifies if the complete icon set should be exported or not (can be very handy for showcases)
completeIconSetName string completeIconSet Name of the generated complete icon set (only effective if exportCompleteIconSet is set to true)
prefix string myIcon prefix for the generated svg constants
interfaceName string MyIcon name for the generated interface
modelFileName string my-icons file name of the generated file
enumName string MyIcons name for the generated enum
delimiter CAMEL, KEBAB, SNAKE, UPPER SNAKE delimiter which is used to generate the types and name properties
srcFiles string "/*.svg" input files matching the given filename pattern
svgoConfig null or config object check help command - to large to display by default we search for a svgo.config.js file in the root or an inline configuration object
outputDirectory string "./dist" name of the output directory
additionalModelOutputPath string null if a path is specified we will generate an additional file containing interface and type to this path - can be useful to improve type safety
iconsFolderName string "build" name of the folder we will build the TypeScript files to
compileSources boolean false If set to false, we generate a TypeScript file for each SVG. If set to true we will allready compile those TypeScript files and generate JavaScript files and declaration files
verbose boolean false defines if the log should contain additional information. Can be useful for debugging

Example usage

Let's say we have the following four svg files in a inputfiles folder.

  • expressionless.svg
  • full.svg
  • laughing.svg
  • smiling-face.svg

We can now run svg-to-ts-files -s ./inputfiles -o ./dist and we end up with the following file in our dist folder.

Sample output

Output scenario two

SVGO - SVG optimization

Under the hood we use the svgo project to optimize the svg icons. To configure SVGO you can add a svgo.config.js file to your root. Check out the official svgo page for further docs about the configuration.

Note: If you dont pass any options, svgo will apply some default options (more)

Starter project

If you want to build a standalone icon library we recommend you to checkout the svg-icon-lib-starter project on GitHub. This project allows you to build an astonishing framework-agnostic SVG icon library with ease. Out of the box icon optimization, build process, and icon showcase. πŸš€

Angular builder

In case you are working with Angular and prefer the usage of a builder we recommend you to check out our offical Angular builder.

FAQ

Which approach should I use

This depends on your use case. If you have a simple application, it's probably enought to go with the single file or even a object. If you build a framework that is used by multiple teams, then you should probably go with the fully tree shakable scenario (generating multiple files).

Is it possilbe to create a standalone library?

Yes, it is. The current configurations also allow you to put your icon registry inside the component library and the icons in a dedicated npm package. This has the following advantages:

  • Icons can be used with different registries
  • Simplified build process
  • Icons can be released independent of the component library
  • No need to let svg-to-ts compile the icons - just set the compile flag to false.

Can I use the icons to generate a type?

If you have a method that decides which icon should be returned its useful to add a return type. To do so you can take advantage of the name subset helper generated by svg-to-ts. The name of the helper will be dynamically generated depending upon the value provided for the interfaceName property. An interfaceName of MyIcon will generate a helper called MyIconNameSubset as shown in the following example.

import {IconNameSubset, myIconSmile, myIconLaugh} from 'my-icon-lib';

type emojiIcons = MyIconNameSubset<[typeof myIconSmile, typeof myIconLaugh]>;

// resulting type is equal to type = 'smile' | 'laugh';

myMethod(): emojiIcons {
  // do stuff here
}

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Kevin Kreuzer

πŸ’» 🎨 πŸ“– πŸ€” πŸš‡ 🚧 ⚠️

Shahar Kazaz

πŸ’» πŸ“– πŸ€” 🚧 ⚠️

Felipe Plets

πŸ’» πŸ“– πŸ€” 🚧 ⚠️

Raphael Ochsenbein

πŸ’» πŸ“– πŸ€” 🚧 ⚠️

Guillaume M

πŸ’» πŸ“– πŸ€” 🚧 ⚠️

Jaime Velay Valor

πŸ’»

Glenn Greibesland

πŸ’»

MrP

πŸ“–

Sebastien Dubois

πŸ“–

Andrew Polhill

πŸ’» πŸ› πŸ“– πŸ€”

Joshua Vinters

πŸ“–

MatthΓ€us G. Chajdas

πŸ“–

Julian Kimmig

πŸ’»

Fernando Montoya

πŸ“–

Alexey Evenkov

πŸ’»

nmastereal

πŸ’»

This project follows the all-contributors specification. Contributions of any kind welcome!