# svgt

A zero-dependency library to transform SVG into components for React, Svelte, Vue, Angular, Astro and Web Components.

## Installation

```bash
npm i @svgt/core
```

## Usage

Import `transform()` and pass it an SVG string and a framework. It returns the component's source code as a string.

```ts
import { transform } from "@svgt/core";

const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M15 18l-6-6 6-6"/></svg>`;

transform(svg, "react", { output: { name: "ArrowLeft" } });
```

### Import a single framework

The main entry point includes every framework. To bundle only one, import `transform()` from its entry point, which takes no `framework` argument:

```ts
import { transform } from "@svgt/core/react";

transform(svg, { output: { name: "ArrowLeft" } });
```

| Framework      | `framework` value  | Entry point                 |
| -------------- | ------------------ | --------------------------- |
| React          | `"react"`          | `@svgt/core/react`          |
| Svelte         | `"svelte"`         | `@svgt/core/svelte`         |
| Vue            | `"vue"`            | `@svgt/core/vue`            |
| Angular        | `"angular"`        | `@svgt/core/angular`        |
| Astro          | `"astro"`          | `@svgt/core/astro`          |
| Web Components | `"web-components"` | `@svgt/core/web-components` |

### Framework details

`@svgt/core/frameworks` describes each framework without importing any transformer. Use it to build a framework picker or to name the generated file:

```ts
import {
  FRAMEWORKS,
  FRAMEWORK_IDS,
  fileName,
  isFramework,
} from "@svgt/core/frameworks";

FRAMEWORK_IDS; // ["react", "svelte", "vue", ...]
FRAMEWORKS.vue.label; // "Vue"
FRAMEWORKS.vue.typescriptOption; // false

fileName("react", "arrow-left"); // "ArrowLeft.tsx (tsx)"
fileName("react", "arrow-left", false); // "ArrowLeft.jsx (jsx)"
fileName("angular", "ArrowLeft"); // "arrow-left.component.ts"
```

| Export                                  | Description                                                                                                               |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `FRAMEWORK_IDS`                         | Every `framework` value, in display order.                                                                                |
| `FRAMEWORKS`                            | Each framework's `label`, whether it accepts the `typescript` option (`typescriptOption`) and its `fileName()`.           |
| `fileName(framework, name, typescript)` | File name for a component, with `name` in PascalCase first. `typescript` defaults to `true`. The CLI uses the same names. |
| `isFramework(value)`                    | Whether a string is a `framework` value. Narrows it to the `Framework` type.                                              |

## Framework outputs

### React

A function component that spreads `props` onto the `<svg>`. Attributes become JSX props (`class` to `className`, `stroke-width` to `strokeWidth`) and inline `style` becomes an object.

```tsx
import type { SVGProps } from "react";

const SvgIcon = (props: SVGProps<SVGSVGElement>) => (
  /// <svg ...props></svg>
);

export default SvgIcon;
```

### Svelte

A Svelte 5 component that reads `$props()` and spreads them onto the `<svg>`.

```svelte
<script lang="ts">
  import type { SVGAttributes } from "svelte/elements";

  let props: SVGAttributes<SVGSVGElement> = $props();
</script>

<svg {...props}>
  <!-- ... -->
</svg>
```

### Vue

A single-file component with only a `<template>`, so attributes fall through to the `<svg>`. Inner `<style>` and `<script>` tags are printed as `<component is="style">` and `<component is="script">`, because Vue doesn't allow them in a template.

```vue
<template>
  <svg>
    <!-- ... -->
  </svg>
</template>
```

### Angular

A standalone component with `OnPush` change detection. Its host element uses `display: contents`, so it doesn't add a box around the `<svg>`. With the default name, the class is `SvgIconComponent` and the selector is `svg-icon`.

```ts
import { ChangeDetectionStrategy, Component } from "@angular/core";

@Component({
  selector: "svg-icon",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { style: "display: contents" },
  template: `
    <svg>
      <!-- ... -->
    </svg>
  `,
})
export class SvgIconComponent {}
```

### Astro

A component that spreads `Astro.props` onto the `<svg>`. Inner `<style>` and `<script>` tags get `is:inline` so Astro leaves them as they are instead of scoping or bundling them.

```astro
---
import type { HTMLAttributes } from "astro/types";

type Props = HTMLAttributes<"svg">;

const props = Astro.props;
---

<svg {...props}>
  <!-- ... -->
</svg>
```

### Web Components

A custom element with a shadow root. It forwards `width`, `height`, `fill`, `stroke` and `stroke-width` from the element to the inner `<svg>`, and registers itself unless the tag is already defined. The class is the default export, or exported directly with [`exportType: "directly"`](#export-type). With TypeScript on, it also adds the tag to `HTMLElementTagNameMap`.

```ts
const template = document.createElement("template");
template.innerHTML = `
  <style>:host { display: inline-flex; }</style>
  <svg><!-- ... --></svg>
`;

class SvgIcon extends HTMLElement {
  static observedAttributes = [
    "width",
    "height",
    "fill",
    "stroke",
    "stroke-width",
  ];

  // ...
}

if (!customElements.get("svg-icon")) {
  customElements.define("svg-icon", SvgIcon);
}

export default SvgIcon;
```

```html
<svg-icon width="32" fill="currentColor"></svg-icon>
```

## Options

Every option is optional.

```ts
transform(svg, "react", {
  typescript: true,
  output: {
    name: "ArrowLeft",
    exportType: "default",
    dimensions: true,
    svgProps: {},
    expandProps: "end",
  },
});
```

| Option               | Type                                            | Default     | Frameworks                           |
| -------------------- | ----------------------------------------------- | ----------- | ------------------------------------ |
| `typescript`         | `boolean`                                       | `true`      | React, Svelte, Astro, Web Components |
| `output.name`        | `string`                                        | `"SvgIcon"` | React, Angular, Web Components       |
| `output.exportType`  | `"default"` or `"directly"`                     | `"default"` | React, Web Components                |
| `output.dimensions`  | `boolean`                                       | `true`      | All                                  |
| `output.svgProps`    | `Record<string, string>`, with `null` to remove | `{}`        | All                                  |
| `output.expandProps` | `"start"`, `"end"` or `false`                   | `"end"`     | React, Svelte, Astro                 |
| `preTransform`       | `(svg: string) => string`                       | —           | All                                  |

### TypeScript

The output is TypeScript by default. Set `typescript` to `false` to get JavaScript:

```ts
transform(svg, "react", { typescript: false });
```

> Vue and Angular don't accept this option, and passing it is a type error: the Vue component has no `<script>`, and Angular components are always TypeScript.

### Name

`output.name` sets the component name and is converted to PascalCase.

```ts
transform(svg, "angular", { output: { name: "ArrowLeft" } });
```

- **React**: the component is `ArrowLeft`.
- **Angular**: the class is `ArrowLeftComponent` (the suffix is not added twice) and the selector is `arrow-left`.
- **Web Components**: the class is `ArrowLeft` and the tag is `arrow-left`. Custom element names need a hyphen, so a one-word name like `Arrow` gets the tag `svg-arrow`.

> Svelte, Vue and Astro ignore it, because those components take their name from the file they're saved in.

### Export type

`output.exportType` sets how the component is exported, in React and Web Components:

- `"default"` (default): `export default ArrowLeft;` at the end.
- `"directly"`: on the declaration, as `export const ArrowLeft = (props) => ...` in React and `export class ArrowLeft extends HTMLElement` in Web Components. Import it with `import { ArrowLeft } from "./ArrowLeft"`.

```ts
transform(svg, "react", {
  output: { name: "ArrowLeft", exportType: "directly" },
});
```

> Svelte, Vue and Astro ignore it, because those components are files. Angular ignores it too: its class is always exported directly.

### Dimensions

`output.dimensions` keeps the `width` and `height` attributes of the root `<svg>`. Set it to `false` to remove them, so the icon is sized with CSS:

```ts
transform(svg, "react", {
  output: { dimensions: false },
});
```

### SVG props

`output.svgProps` adds, replaces or removes attributes of the root `<svg>`. A string sets the attribute, and `null` removes it:

```ts
transform(svg, "react", {
  output: {
    svgProps: {
      "aria-hidden": "true",
      "stroke-width": "1.5",
      class: null,
    },
  },
});
```

- Use the SVG attribute names, as in the `.svg` file. Each framework prints them with its own syntax, so `stroke-width` becomes `strokeWidth` in React.
- It runs after `dimensions`, so `{ dimensions: false, svgProps: { width: "1em", height: "1em" } }` replaces the original size with `1em`.
- The values are static strings. Props passed to the component still override them where the framework spreads them onto the `<svg>`.

### Expand props

`output.expandProps` sets where the component's props are spread on the root `<svg>`:

- `"end"` (default): after the SVG's attributes, so props passed to the component override them.
- `"start"`: before them, so the SVG's attributes win.
- `false`: not spread. The component doesn't declare props at all.

```ts
transform(svg, "react", {
  output: { expandProps: "start" },
});
```

- It runs after `svgProps`, so with `"end"` props also override the attributes set there.
- Vue, Angular and Web Components ignore it: Vue passes attributes through on its own, and the others don't spread props.

### Pre-transform

`preTransform` runs on the SVG string before svgt parses it, and returns the SVG string to transform.

#### SVGO

Example with [SVGO](https://github.com/svg/svgo):

```ts
import { optimize } from "svgo";
import { transform } from "@svgt/core";

transform(svg, "react", {
  preTransform: (svg) => optimize(svg, { multipass: true }).data,
});
```

## Errors

`transform()` throws an `Error` prefixed with `[svgt]` when the SVG can't be parsed, such as `[svgt] Unclosed tag <div> (at position 5)`. It also throws when `preTransform` throws (`[svgt] preTransform failed: ...`, with the original error as `cause`) or doesn't return a string, when `output.svgProps` has an invalid attribute name (`[svgt] Invalid attribute name in svgProps: "1bad"`), when `output.exportType` isn't `"default"` or `"directly"`, and when `output.expandProps` isn't `"start"`, `"end"` or `false`.

## References

- [gregberge/svgr](https://react-svgr.com/) - Transform SVGs into React components.
- [SVGO](https://github.com/svg/svgo) - SVG Optimizer for Node.js and CLI.

## License

MIT
