Skip to content

Throw useful errors in dev #29

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

Merged
merged 1 commit into from
Mar 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,27 @@ export const transformRawValue = (input) => {
return value ? Number(value[1]) : input;
};

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

const transformShorthandValue = (process.env.NODE_ENV === 'production')
? baseTransformShorthandValue
: (propName, inputValue) => {
try {
return baseTransformShorthandValue(propName, inputValue);
} catch (e) {
throw new Error(`Failed to parse declaration "${propName}: ${inputValue}"`);
}
};

export const getStylesForProperty = (propName, inputValue, allowShorthand) => {
const isRawValue = (allowShorthand === false) || !(propName in transforms);
if (isRawValue) {
const value = typeof inputValue === 'string' ? inputValue : parse.stringify(inputValue);
propValue = transformRawValue(value);
} else {
const ast = typeof inputValue === 'string' ? parse(inputValue.trim()) : inputValue;
const tokenStream = new TokenStream(ast.nodes);
propValue = transforms[propName](tokenStream);
}
const propValue = isRawValue
? transformRawValue(inputValue)
: transformShorthandValue(propName, inputValue.trim());

return (propValue && propValue.$merge)
? propValue.$merge
Expand Down
5 changes: 5 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -393,3 +393,8 @@ it('allows blacklisting shorthands', () => {
const actualStyles = transformCss([['border-radius', '50']], ['borderRadius']);
expect(actualStyles).toEqual({ borderRadius: 50 });
});

it('throws useful errors', () => {
expect(() => transformCss([['margin', '10']]))
.toThrow('Failed to parse declaration "margin: 10"');
});