From ac4edb827dac88b2cfbb53af739d609bfa588a0d Mon Sep 17 00:00:00 2001 From: Jacob Parker Date: Sat, 4 Mar 2017 12:12:07 +0000 Subject: [PATCH] Throw useful errors in dev --- src/index.js | 30 +++++++++++++++++++----------- src/index.test.js | 5 +++++ 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/src/index.js b/src/index.js index 566b73d..6591e72 100644 --- a/src/index.js +++ b/src/index.js @@ -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 diff --git a/src/index.test.js b/src/index.test.js index 19a5003..0a68783 100644 --- a/src/index.test.js +++ b/src/index.test.js @@ -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"'); +});