Skip to content

Commit a944c5a

Browse files
authored
Merge pull request styled-components#29 from styled-components/useful-errors
Throw useful errors in dev
2 parents ac4ee18 + ac4edb8 commit a944c5a

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

src/index.js

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,27 @@ export const transformRawValue = (input) => {
1313
return value ? Number(value[1]) : input;
1414
};
1515

16-
export const getStylesForProperty = (propName, inputValue, allowShorthand) => {
17-
// Undocumented: allow ast to be passed in
18-
let propValue;
16+
const baseTransformShorthandValue = (propName, inputValue) => {
17+
const ast = parse(inputValue.trim());
18+
const tokenStream = new TokenStream(ast.nodes);
19+
return transforms[propName](tokenStream);
20+
};
1921

22+
const transformShorthandValue = (process.env.NODE_ENV === 'production')
23+
? baseTransformShorthandValue
24+
: (propName, inputValue) => {
25+
try {
26+
return baseTransformShorthandValue(propName, inputValue);
27+
} catch (e) {
28+
throw new Error(`Failed to parse declaration "${propName}: ${inputValue}"`);
29+
}
30+
};
31+
32+
export const getStylesForProperty = (propName, inputValue, allowShorthand) => {
2033
const isRawValue = (allowShorthand === false) || !(propName in transforms);
21-
if (isRawValue) {
22-
const value = typeof inputValue === 'string' ? inputValue : parse.stringify(inputValue);
23-
propValue = transformRawValue(value);
24-
} else {
25-
const ast = typeof inputValue === 'string' ? parse(inputValue.trim()) : inputValue;
26-
const tokenStream = new TokenStream(ast.nodes);
27-
propValue = transforms[propName](tokenStream);
28-
}
34+
const propValue = isRawValue
35+
? transformRawValue(inputValue)
36+
: transformShorthandValue(propName, inputValue.trim());
2937

3038
return (propValue && propValue.$merge)
3139
? propValue.$merge

src/index.test.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,3 +393,8 @@ it('allows blacklisting shorthands', () => {
393393
const actualStyles = transformCss([['border-radius', '50']], ['borderRadius']);
394394
expect(actualStyles).toEqual({ borderRadius: 50 });
395395
});
396+
397+
it('throws useful errors', () => {
398+
expect(() => transformCss([['margin', '10']]))
399+
.toThrow('Failed to parse declaration "margin: 10"');
400+
});

0 commit comments

Comments
 (0)