Ad

Babel Es2015 Arrow Function Error

- 1 answer

I'm using es2015 Arrow functions in a React component that is throwing an error when I declare myfunction() {...}. The error doesn't exist if write it like so myFunction : function () {...}. I do not have any issues compiling with Browserify/Babelify - this only happens with the below example.

import React from 'react';

module.exports =  React.createClass({
  // render : function () { // <--- this works
  render() { // <---- this throws an error
    return (
      <div>Kaboom.</div>
      );
  }
});

/* RenderService.js */
require("babel-register")({
  plugins: ["transform-react-jsx","transform-es2015-modules-commonjs"]
});

var React = require('react');
var ReactDOMServer = require('react-dom/server');

module.exports = {
  renderReport : function (reportId) {
    var TestComp =  require('./TestCompoennt');

    var ReactComponent = React.createFactory(TestComp,'div');

    return ReactDOMServer.renderToStaticMarkup(ReactComponent());
  }
};

Error: renderApproval() { ^ SyntaxError: Unexpected token (

Ad

Answer

Maybe you should use a preset-es2015, this plugin includes transform-es2015-shorthand-properties, that one you need to transform this:

var z = function() { return 'z'; };
var x = {
  z
}

to this:

var z = function() { return 'z'; };
var x = {
  z: z
}

Or in your case

var x = {
  z() {
    return 'z';
  }
}

And also includes:

  • check-es2015-constants
  • transform-es2015-arrow-functions
  • transform-es2015-block-scoped-functions
  • transform-es2015-block-scoping
  • transform-es2015-classes
  • transform-es2015-computed-properties
  • transform-es2015-destructuring
  • transform-es2015-for-of
  • transform-es2015-function-name
  • transform-es2015-literals
  • transform-es2015-modules-commonjs
  • transform-es2015-object-super
  • transform-es2015-parameters
  • transform-es2015-shorthand-properties
  • transform-es2015-spread
  • transform-es2015-sticky-regex
  • transform-es2015-template-literals
  • transform-es2015-typeof-symbol
  • transform-es2015-unicode-regex
  • transform-regenerator

Link http://babeljs.io/docs/plugins/preset-es2015/

Ad
source: stackoverflow.com
Ad