Skip to content

Commit

Permalink
adding configs to options
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Hallock committed Aug 13, 2021
1 parent 8e3e007 commit 8849a80
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 15 deletions.
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@ import svgrPlugin from 'vite-plugin-svgr'

export default {
// ...
plugins: [svgrPlugin()],
plugins: [
svgrPlugin({
svgr: {/* SVGR config */},
svgrState: {/* SVGR state */},
esbuild: {/* esbuild config */},
defaultExport: false, // uses export default when true. See typescript section below
})
],
}
```

Expand All @@ -22,7 +29,9 @@ Then SVG files can be imported as React components, just like [create-react-app]
import { ReactComponent as Logo } from './logo.svg'
```

If you are using TypeScript, `vite-plugin-svgr/client` can be added to `tsconfig.json`:
### TypeScript

Add `vite-plugin-svgr/client` (or `vite-plugin/client-default` if using `options.defaultExport`) to [`compilerOptions.types`](https://www.typescriptlang.org/tsconfig#types) in `tsconfig.json`:

```json
{
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"dev": "tsc --watch",
"build": "tsc",
"prepublish": "npm run build"
"prepare": "npm run build"
},
"repository": {
"type": "git",
Expand Down
30 changes: 18 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import fs from 'fs'
import type { Plugin } from 'vite'
import type {Plugin} from 'vite'
import type * as E from 'esbuild'

export = function svgrPlugin(): Plugin {
// TODO: options
export interface Options {
svgr?: {};
svgrState?: {};
esbuild?: {}
exportName?: string;
};

export default function svgrPlugin(options?: Options): Plugin {
return {
name: 'vite:svgr',
async transform(code, id) {
async transform(code: string, id: string) {
if (id.endsWith('.svg')) {
const svgr = require('@svgr/core').default
const esbuild = require('esbuild') as typeof E
Expand All @@ -15,22 +21,22 @@ export = function svgrPlugin(): Plugin {

const componentCode = await svgr(
svg,
{},
{ componentName: 'ReactComponent' }
{...options?.svgr},
{componentName: 'ReactComponent', ...options?.svgrState}
).then((res: string) => {
return res.replace(
'export default ReactComponent',
`export { ReactComponent }`
)
return options?.exportName !== "default" ? res.replace(
/export default ([a-zA-Z0-9_$]+)/,
`export { $1 }`
) : res;
})

const res = await esbuild.transform(componentCode + '\n' + code, {
loader: 'jsx',
...options?.esbuild
})

return {
code: res.code,
map: null, // TODO:
map: null,
}
}
},
Expand Down

0 comments on commit 8849a80

Please sign in to comment.