Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate typescript for SVGs when using svgr and typescript option #8411

Merged
merged 13 commits into from
Sep 7, 2022
Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"typescript": true
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<img src="icon.svg" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"source": "react.ts",
"main": "icons.js",
"types": "types.d.ts",
"dependencies": {
"react": "*"
}
}
Original file line number Diff line number Diff line change
@@ -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;
17 changes: 17 additions & 0 deletions packages/core/integration-tests/test/svg-react.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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