atlowChemi / vite-svg-2-webfont

A vite plugin which generates a webfont out of svg icons
https://www.npmjs.com/package/vite-svg-2-webfont
MIT License
24 stars 8 forks source link
font font-icons icons svg svg-icons vite vite-plugin webfonts-generator webfonts-loader

vite-svg-2-webfont

npm GitHub Actions Workflow Status npm license npm bundle size node engine Package Quality

A Vite Plugin that generates fonts from your SVG icons and allows you to use your icons in your HTML.

vite-svg-2-webfont uses the webfonts-generator package to create fonts in any format. It also generates CSS files so that you can use your icons directly in your HTML, using CSS classes.

Installation

NPM

npm i -D vite-svg-2-webfont

YARN

yarn add -D vite-svg-2-webfont

PNPM

pnpm add -D vite-svg-2-webfont

Usage

Add the plugin to the vite.config.ts with the wanted setup, and import the virtual module, to inject the icons CSS font to the bundle.

Vite config

Add the plugin to your vite configs plugin array.

// vite.config.ts
import { resolve } from 'path';
import { defineConfig } from 'vite';
import viteSvgToWebfont from 'vite-svg-2-webfont';

export default defineConfig({
    plugins: [
        viteSvgToWebfont({
            context: resolve(__dirname, 'icons'),
        }),
    ],
});

Import virtual module

Import the virtual module into the app

// main.ts
import 'virtual:vite-svg-2-webfont.css';

Add class-name to HTML element to use font

Use the font in templates with the icon font class and an icon class name. The default font class name is .icon and can be overriden by passing the baseSelector configuration option. Icon class names are derived from their .svg file name, and prefixed with the value of classPrefix which defaults to icon-.

In the below example, the add class would display the icon created from the file {context}/add.svg

<i class="icon icon-add"></i>

Configuration

The plugin has an API consisting of one required parameter and multiple optional parameters allowing to fully customize plugin setup.

context

files

fontName

dest

cssDest

cssTemplate

cssContext

cssFontsUrl

htmlDest

htmlTemplate

ligature

normalize

round

descent

fixedWidth

fontHeight

centerHorizontally

generateFiles

types

codepoints

classPrefix

baseSelector

formatOptions

moduleId

inline

allowWriteFilesInBuild

Public API

The plugin exposes a public API that can be used inside another plugins using Rollup inter-plugin communication mechanism.

Currently available methods:

getGeneratedWebfonts