Skip to content

Commit c03fd77

Browse files
authored
Merge pull request #8 from lencioni/default-props
Use defaultProps instead of adding props to the svg
2 parents de5717c + e3ffce9 commit c03fd77

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
@@ -13,6 +13,11 @@ const buildSvg = template(`
1313
var SVG_NAME = function SVG_NAME(props) { return SVG_CODE; };
1414
`);
1515

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

1823
export default ({ types: t }) => ({
@@ -52,12 +57,40 @@ export default ({ types: t }) => ({
5257

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

55-
const svgReplacement = buildSvg({
60+
const opts = {
5661
SVG_NAME: importIdentifier,
5762
SVG_CODE: svgCode,
58-
});
63+
};
64+
65+
// Move props off of element and into defaultProps
66+
if (svgCode.openingElement.attributes.length > 1) {
67+
const keepProps = [];
68+
const defaultProps = [];
5969

60-
path.replaceWith(svgReplacement);
70+
svgCode.openingElement.attributes.forEach((prop) => {
71+
if (prop.type === 'JSXSpreadAttribute') {
72+
keepProps.push(prop);
73+
} else {
74+
defaultProps.push(
75+
t.objectProperty(
76+
t.identifier(prop.name.name),
77+
prop.value,
78+
)
79+
);
80+
}
81+
});
82+
83+
svgCode.openingElement.attributes = keepProps;
84+
opts.SVG_DEFAULT_PROPS_CODE = t.objectExpression(defaultProps);
85+
}
86+
87+
if (opts.SVG_DEFAULT_PROPS_CODE) {
88+
const svgReplacement = buildSvgWithDefaults(opts);
89+
path.replaceWithMultiple(svgReplacement);
90+
} else {
91+
const svgReplacement = buildSvg(opts);
92+
path.replaceWith(svgReplacement);
93+
}
6194
}
6295
},
6396
},

0 commit comments

Comments
 (0)