From 8c5f27affcdd16823629c8121247f6f8274cfdda Mon Sep 17 00:00:00 2001 From: Rongjian Zhang Date: Sat, 9 Jan 2021 15:53:00 +0800 Subject: [PATCH] feat: initial version --- README.md | 19 ++++++++++++++++++- package.json | 14 ++++++++++++-- src/index.ts | 39 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 68 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index edf5f0f..6dfd6ac 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,19 @@ # vite-plugin-svgr -Vite plugin to transform SVGs into React components + +Vite plugin to transform SVGs into React components. Uses [svgr](https://github.com/gregberge/svgr) under the hood. + +## Usage + +```js +// vite.config.js +import svgr from 'vite-plugin-svgr' + +export default { + // ... + plugins: [svgr()], +} +``` + +## License + +MIT diff --git a/package.json b/package.json index 5a2fff8..2c0d9f5 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,9 @@ "description": "Vite plugin to transform SVGs into React components", "main": "lib/index.js", "scripts": { - "dev": "tsc --watch" + "dev": "tsc --watch", + "build": "tsc", + "prepublish": "npm run build" }, "repository": { "type": "git", @@ -23,6 +25,14 @@ }, "homepage": "https://github.com/pd4d10/vite-plugin-svgr#readme", "devDependencies": { - "typescript": "^4.1.3" + "typescript": "^4.1.3", + "vite": "^2.0.0-beta.15", + "@types/node": "^14.14.20" + }, + "peerDependencies": { + "vite": "^2.0.0-beta.1" + }, + "dependencies": { + "@svgr/core": "^5.5.0" } } diff --git a/src/index.ts b/src/index.ts index 371fdfb..2565414 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1 +1,38 @@ -console.log('hello') +import fs from 'fs' +import type { Plugin } from 'vite' +import type * as E from 'esbuild' + +export = function svgrPlugin(): Plugin { + // TODO: options + return { + name: 'vite:svgr', + async transform(code, id) { + if (id.endsWith('.svg')) { + const svgr = require('@svgr/core').default + const esbuild = require('esbuild') as typeof E + + const svg = await fs.promises.readFile(id, 'utf8') + + const componentCode = await svgr( + svg, + {}, + { componentName: 'ReactComponent' } + ).then((res: string) => { + return res.replace( + 'export default ReactComponent', + `export { ReactComponent }` + ) + }) + + const res = await esbuild.transform(componentCode + '\n' + code, { + loader: 'jsx', + }) + + return { + code: res.code, + map: res.map, + } + } + }, + } +}