I need to make my javascript (which is in a non-Node.js environment) backwards compatible so I'm trying to utilize Babel to transpile my code as suggested in this post
babel-standalone works great except it doesnt seem to work with the spread/rest operator
For example, the following works great:
var input = 'const getMessage = (D) => {return D}';
var output = Babel.transform(input, { presets: ['es2015'] }).code;
However, the following generates an error:
var input = 'const getMessage = (D) => {...D}';
var output = Babel.transform(input, { presets: ['es2015'] }).code;
Error Below
babel.min.js:2 Uncaught SyntaxError: unknown: Unexpected token (1:26)
> 1 | const getMessage = (D) => return {D}
| ^
babel.min.js:2 Uncaught SyntaxError: unknown: Unexpected token (1:27)
> 1 | const getMessage = (D) => {...D}
| ^
at t.J.raise (babel.min.js:7)
at t.X.unexpected (babel.min.js:5)
at te.parseExprAtom (babel.min.js:6)
at te.parseExprSubscripts (babel.min.js:6)
at te.parseMaybeUnary (babel.min.js:6)
at te.parseExprOps (babel.min.js:6)
at te.parseMaybeConditional (babel.min.js:6)
at te.parseMaybeAssign (babel.min.js:6)
at te.parseExpression (babel.min.js:6)
at t.z.parseStatement (babel.min.js:5)
babel.js:14449 Uncaught SyntaxError: unknown: Unexpected token (1:27)
> 1 | const getMessage = (D) => {...D}
| ^
at Parser.pp$5.raise (babel.js:14449)
at Parser.pp.unexpected (babel.js:11756)
at Parser.pp$3.parseExprAtom (babel.js:13745)
at Parser.pp$3.parseExprSubscripts (babel.js:13489)
at Parser.pp$3.parseMaybeUnary (babel.js:13469)
at Parser.pp$3.parseExprOps (babel.js:13399)
at Parser.pp$3.parseMaybeConditional (babel.js:13376)
at Parser.pp$3.parseMaybeAssign (babel.js:13339)
at Parser.pp$3.parseExpression (babel.js:13301)
at Parser.pp$1.parseStatement (babel.js:11901)
The babel-standalone github page states "It's bundled with all the standard Babel plugins and presets," yet it cant seem to transpile my usage of the spread operator
{}
after an arrow function is treated as a function block, not as an implicit return of an object. So your first example is really just creating a function with doesn't return anything. So trying to spread into a function block{...D}
will give an error. To return an object encase the object in parenthesesconst getMessage = (D) => ({...D})
<--- valid syntax(D) => return {D}
should be(D) => {return D}