Skip to content

Commit e3ffce9

Browse files
committed
Use defaultProps instead of adding props to the svg
Currently, when transforming an SVG file that has attributes on the top-level `<svg>` element, the transformed component ends up looking something like this: ```js _extends({ xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 1000 1000' }, props), ``` this adds the overhead of _extends. I think it might be a better to instead move these values into `defaultProps` on the generated component. Closes #7
1 parent 46ea005 commit e3ffce9

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

src/index.js

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ const buildSvg = template(`
1212
var SVG_NAME = function SVG_NAME(props) { return SVG_CODE; };
1313
`);
1414

15+
const buildSvgWithDefaults = template(`
16+
var SVG_NAME = function SVG_NAME(props) { return SVG_CODE; };
17+
SVG_NAME.defaultProps = SVG_DEFAULT_PROPS_CODE;
18+
`);
19+
1520
let ignoreRegex;
1621

1722
export default ({ types: t }) => ({
@@ -45,12 +50,40 @@ export default ({ types: t }) => ({
4550

4651
const svgCode = traverse.removeProperties(parsedSvgAst.program.body[0].expression);
4752

48-
const svgReplacement = buildSvg({
53+
const opts = {
4954
SVG_NAME: importIdentifier,
5055
SVG_CODE: svgCode,
51-
});
56+
};
57+
58+
// Move props off of element and into defaultProps
59+
if (svgCode.openingElement.attributes.length > 1) {
60+
const keepProps = [];
61+
const defaultProps = [];
5262

53-
path.replaceWith(svgReplacement);
63+
svgCode.openingElement.attributes.forEach((prop) => {
64+
if (prop.type === 'JSXSpreadAttribute') {
65+
keepProps.push(prop);
66+
} else {
67+
defaultProps.push(
68+
t.objectProperty(
69+
t.identifier(prop.name.name),
70+
prop.value,
71+
)
72+
);
73+
}
74+
});
75+
76+
svgCode.openingElement.attributes = keepProps;
77+
opts.SVG_DEFAULT_PROPS_CODE = t.objectExpression(defaultProps);
78+
}
79+
80+
if (opts.SVG_DEFAULT_PROPS_CODE) {
81+
const svgReplacement = buildSvgWithDefaults(opts);
82+
path.replaceWithMultiple(svgReplacement);
83+
} else {
84+
const svgReplacement = buildSvg(opts);
85+
path.replaceWith(svgReplacement);
86+
}
5487
}
5588
},
5689
},

0 commit comments

Comments
 (0)