Compared to svgr, svgj is buggier, has a worse API, fewer features, only returns JSX as strings that need to be transpiled, and prints ugly looking JSX.
But its much faster, thanks to using htmlparser2 and serialization logic from dom-serializer (with modifications to support JSX and passing in custom props based on element). Consequently, this will often work with html.
You probably only want to use this inside of a bundler when importing SVG files as JSX.
Usage
You probably want to use the esbuild plugin instead of the underlying library.
Installation
yarn:
yarn add esbuild-plugin-svgj
npm:
npm install esbuild-plugin-svgj
esbuild-plugin-svgj usage
import { plugin } from "esbuild-plugin-svgj";import { readFile } from "fs/promises";import esbuild from "esbuild";esbuild.build({ // ...rest of esbuild config plugins: [ plugin({ readFile: (path) => readFile(path, "utf8"), }), ],});
The first group renders 10 svgs. The second group renders a single svg. The svg files are read from disk as strings before the benchmark starts.
❯ node bench.mjssvgj x 10,271 ops/sec ±1.06% (90 runs sampled)svgr sync x 105 ops/sec ±4.86% (74 runs sampled)Fastest is svgjSlowest is svgr syncsvgj x 89,124 ops/sec ±1.45% (90 runs sampled)svgr sync x 1,199 ops/sec ±2.01% (81 runs sampled)Fastest is svgjSlowest is svgr sync
Then, run node bench-async.mjs
benchmark.js is a little tough to get working right with async code, so this one just uses console.time, but with a warmup beforehand. The files in both benchmarks are the same.
Keep in mind that this currently won't React.forwardRef. Per create-react-app's defaults, src is the source string and ReactComponent is the JSX source.