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
@@ -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;
32 changes: 32 additions & 0 deletions packages/core/integration-tests/test/svg-react-typescript.js
@@ -0,0 +1,32 @@
import assert from 'assert';
import {bundle, outputFS} from '@parcel/test-utils';
import path from 'path';

describe('svg-react-typescript', () => {
samjt marked this conversation as resolved.
Show resolved Hide resolved
let file, types, b;
before(async () => {
b = await bundle(
path.join(__dirname, '/integration/svg-react-typescript/react.ts'),
{
defaultConfig: path.join(
__dirname,
'integration/custom-configs/.parcelrc-svg-react',
),
defaultTargetOptions: {
typescript: true,
},
},
);
file = await outputFS.readFile(b.getBundles()[0].filePath, 'utf-8');
types = await outputFS.readFile(b.getBundles()[1].filePath, 'utf-8');
});

it('should support transforming SVGs to typescript react components', function () {
assert(!file.includes('inkscape'));
assert(file.includes('react.createElement("svg"'));
});

it('should support generating typescript types for SVG react components', function () {
assert(types.includes('const Icon: SVGRComponent'));
});
});
10 changes: 8 additions & 2 deletions packages/transformers/svg-react/src/SvgReactTransformer.js
Expand Up @@ -17,7 +17,13 @@ function getComponentName(filePath) {
}

export default (new Transformer({
async transform({asset}) {
async loadConfig({config}) {
let {contents} =
(await config.getConfig(['.svgrrc.json', '.svgrrc'])) || {};

return contents;
samjt marked this conversation as resolved.
Show resolved Hide resolved
},
async transform({asset, config}) {
let code = await asset.getCode();
let componentName = getComponentName(asset.filePath);

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

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

Expand Down