Skip to content

Commit

Permalink
Initial commit [publish]
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnaudBarre committed Feb 2, 2022
0 parents commit 09c5d81
Show file tree
Hide file tree
Showing 10 changed files with 443 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .github/workflows/publish.yml
@@ -0,0 +1,17 @@
name: Publish to npm
on:
push:
branches:
- main
jobs:
publish:
runs-on: ubuntu-latest
if: ${{ contains(github.event.head_commit.message, '[publish]') }}
steps:
- uses: actions/checkout@v2
- run: yarn install --frozen-lockfile
- run: yarn prettier-ci
- run: yarn build
- uses: ArnaudBarre/npm-publish@v1
with:
npm-token: ${{ secrets.NPM_TOKEN }}
3 changes: 3 additions & 0 deletions .gitignore
@@ -0,0 +1,3 @@
.idea/
node_modules/
dist/
5 changes: 5 additions & 0 deletions CHANGELOG.md
@@ -0,0 +1,5 @@
# Changelog

## 0.1.0

Initial release
21 changes: 21 additions & 0 deletions LICENSE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Arnaud Barré (https://github.com/ArnaudBarre)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
48 changes: 48 additions & 0 deletions README.md
@@ -0,0 +1,48 @@
# vite-plugin-fast-react-svg [![npm](https://img.shields.io/npm/v/vite-plugin-fast-react-svg)](https://www.npmjs.com/package/vite-plugin-fast-react-svg)

Turn SVG into React components, without Babel.

## Why

While [svgr](https://github.com/gregberge/svgr) is great, it uses AST transformation from Babel, which is too slow (~300ms per SVG). This plugin uses regex manipulations for SVG -> JSX and esbuild for JSX -> JS (~10ms in average). It's working well for SVG optimized by [svgo](https://github.com/svg/svgo). This plugin will **not** run svgo, so you should run it beforehand and commit the cleaned version.

## Installation

```sh
npm i -D vite-plugin-fast-react-svg
```

In your vite config:

```ts
import { defineConfig } from "vite";
import svgPlugin from "vite-plugin-fast-react-svg";

export default defineConfig({
plugins: [svgPlugin()],
});
```

In `tsconfig.json`:

```json5
{
compilerOptions: {
types: ["vite-plugin-fast-react-svg/types", "vite/client"],
},
}
```

## Usage

```jsx
import Logo from "./logo.svg";
import base64Data from "./logo.svg?inline";

const Example = () => (
<>
<Logo />
<img src={base64Data} alt="Logo" />
</>
);
```
35 changes: 35 additions & 0 deletions package.json
@@ -0,0 +1,35 @@
{
"name": "vite-plugin-fast-react-svg",
"description": "Turn SVG into React components, without Babel",
"version": "0.1.0",
"license": "MIT",
"author": "Arnaud Barré (https://github.com/ArnaudBarre)",
"main": "dist/index.js",
"files": [
"dist",
"types.d.ts"
],
"repository": "github:ArnaudBarre/vite-plugin-fast-react-svg",
"keywords": [
"vite",
"vite-plugin",
"react",
"svg"
],
"scripts": {
"build": "tsc",
"prettier": "yarn prettier-ci --write",
"prettier-ci": "prettier --check '**/*.{ts,json,md,yml}'"
},
"peerDependencies": {
"react": ">=16",
"vite": "^2"
},
"devDependencies": {
"@types/node": "^17.0.13",
"@types/react": "^17.0.38",
"prettier": "^2.5.1",
"typescript": "^4.5.5",
"vite": "^2.7.13"
}
}
43 changes: 43 additions & 0 deletions src/index.ts
@@ -0,0 +1,43 @@
import { readFileSync } from "fs";
import { transform } from "esbuild";
import { Plugin } from "vite";

export default function svgPlugin(): Plugin {
return {
name: "svg",
enforce: "pre",
load(id) {
if (id.endsWith(".svg")) {
return readFileSync(id, "utf-8");
}
if (id.endsWith(".svg?inline")) {
return readFileSync(id.replace("?inline", ""), "utf-8");
}
},
transform(code, id) {
if (id.endsWith(".svg")) {
return transform(svgToJSX(code), { loader: "jsx" });
}
if (id.endsWith(".svg?inline")) {
const base64 = Buffer.from(code).toString("base64");
return `export default "data:image/svg+xml;base64,${base64}"`;
}
},
};
}

const svgToJSX = (svg: string) =>
`import React from "react";const ReactComponent = (props) => (${svg
.replace(/\s([a-z-:]*)="[^"]*"/gu, (string, key: string) => {
if (key.startsWith("data-")) return string;
const keyWithoutDashes = camelCaseOn(key, "-");
const keyWithoutDots = camelCaseOn(keyWithoutDashes, ":");
return string.replace(key, keyWithoutDots);
})
.replace(">", " {...props}>")});export default ReactComponent`;

const camelCaseOn = (string: string, delimiter: string) =>
string
.split(delimiter)
.map((v, i) => (i === 0 ? v : v[0].toUpperCase() + v.slice(1)))
.join("");
23 changes: 23 additions & 0 deletions tsconfig.json
@@ -0,0 +1,23 @@
{
"include": ["src"],
"compilerOptions": {
/* Target node12 */
"module": "CommonJS",
"lib": ["ES2019"],
"target": "ES2019",
"declaration": true,
"outDir": "dist",

/* Imports */
"moduleResolution": "node", // Allow `index` imports
"resolveJsonModule": true, // Allow json import
"forceConsistentCasingInFileNames": true, // Avoid difference in case between file name and import

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"useUnknownInCatchVariables": true
}
}
12 changes: 12 additions & 0 deletions types.d.ts
@@ -0,0 +1,12 @@
declare module "*.svg" {
import { FunctionComponent, SVGProps } from "react";
const ReactComponent: FunctionComponent<
SVGProps<SVGSVGElement> & { title?: string }
>;
export default ReactComponent;
}

declare module "*.svg?inline" {
const data: string;
export default data;
}

0 comments on commit 09c5d81

Please sign in to comment.