Skip to content

Commit

Permalink
feat: initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
pd4d10 committed Jan 9, 2021
1 parent 7d1de2b commit 8c5f27a
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 4 deletions.
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -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
14 changes: 12 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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"
}
}
39 changes: 38 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -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,
}
}
},
}
}

0 comments on commit 8c5f27a

Please sign in to comment.