Skip to content

Commit

Permalink
Generate typescript for SVGs when using svgr and typescript option (#…
Browse files Browse the repository at this point in the history
…8411)

Co-authored-by: Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
  • Loading branch information
samjt and mischnic committed Sep 7, 2022
1 parent 65500fb commit 1572df0
Show file tree
Hide file tree
Showing 8 changed files with 57 additions and 2 deletions.
@@ -0,0 +1,3 @@
{
"typescript": true
}
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@@ -0,0 +1 @@
<img src="icon.svg" />
@@ -0,0 +1,8 @@
{
"source": "react.ts",
"main": "icons.js",
"types": "types.d.ts",
"dependencies": {
"react": "*"
}
}
@@ -0,0 +1,8 @@

interface SVGRComponent
extends React.StatelessComponent<React.SVGAttributes<SVGElement>> {}

import React from 'react';
import ReactIcon from './icon.svg';
const Icon:SVGRComponent = ReactIcon;
export default Icon;
Empty file.
17 changes: 17 additions & 0 deletions packages/core/integration-tests/test/svg-react.js
Expand Up @@ -19,4 +19,21 @@ describe('svg-react', function () {
assert(file.includes('const SvgIcon ='));
assert(file.includes('_react.createElement("svg"'));
});
it('should support transforming SVGs to typescript react components', async function () {
let b = await bundle(
path.join(__dirname, '/integration/svg-react-typescript/react.ts'),
{
defaultConfig: path.join(
__dirname,
'integration/custom-configs/.parcelrc-svg-react',
),
},
);
let file = await outputFS.readFile(b.getBundles()[0].filePath, 'utf-8');
let types = await outputFS.readFile(b.getBundles()[1].filePath, 'utf-8');

assert(!file.includes('inkscape'));
assert(file.includes('react.createElement("svg"'));
assert(types.includes('const Icon: SVGRComponent'));
});
});
8 changes: 6 additions & 2 deletions packages/transformers/svg-react/src/SvgReactTransformer.js
Expand Up @@ -17,7 +17,11 @@ function getComponentName(filePath) {
}

export default (new Transformer({
async transform({asset}) {
async loadConfig({config}) {
let conf = await config.getConfig(['.svgrrc.json', '.svgrrc']);
return conf?.contents;
},
async transform({asset, config}) {
let code = await asset.getCode();
let componentName = getComponentName(asset.filePath);

Expand All @@ -33,7 +37,7 @@ export default (new Transformer({
},
);

asset.type = 'jsx';
asset.type = config?.typescript ? 'tsx' : 'jsx';
asset.bundleBehavior = null;
asset.setCode(jsx);

Expand Down

0 comments on commit 1572df0

Please sign in to comment.