reactjsecmascript-6syntax-errorbabeljsbrunch

Brunch.io with React and Babel Syntax Error


I'm using Brunch.io for the first time to build a new React app. It all seems to work fine but the moment I try and set state or use an arrow function I get a syntax error. My guess is that I'm missing a Babel preset or another piece of config.

Can someone help or have any idea what this missing piece might be?

Console error:

09:27:18 - error: Compiling of app/components/index.js failed. Error: SyntaxError: app/components/index.js: Unexpect
ed token (10:15)
      |      * @return {string}    formatted list of authors
      |      */
   >  |     getAuthors = (arr) => {
      |                ^
      |         if (arr) {
      |             return arr.join('\r\n');
      |         } else {

package.json

{
  "name": "brunch-app",
  "description": "Brunch.io application",
  "private": true,
  "author": "Brunch",
  "version": "0.0.1",
  "repository": "",
  "scripts": {
    "start": "brunch watch --server",
    "build": "brunch build --production"
  },
  "dependencies": {
    "prop-types": "^15.6.0",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-redux": "^5.0.6",
    "react-router-dom": "^4.2.2",
    "redux": "^3.7.2"
  },
  "devDependencies": {
    "auto-reload-brunch": "^2",
    "hmr-brunch": "^0.1",
    "babel-brunch": "~6.0.0",
    "babel-preset-latest": "^6",
    "babel-preset-react": "~6.22",
    "brunch": "^2",
    "clean-css-brunch": "^2",
    "uglify-js-brunch": "^2"
  }
}

brunch-config.js:

exports.files = {
  javascripts: {
    joinTo: 'app.js'
  },
  stylesheets: {joinTo: 'app.css'}
};

exports.plugins = {
  babel: {presets: ['es2015', 'react']}
};

exports.hot = true;

components/index.js fails to compile:

import React from 'react';

class Book extends React.Component {

    state = {
        authors: [],
        books: [],
    };

    getAuthors = (arr) => {
        if (arr) {
            return arr.join('\r\n');
        } else {
            return 'Unknown author';
        }
    };

    render() {

        return (
            <li>
                {book.authors && book.authors.map((author) => (
                    <span className='book-authors'>{author}</span>
                ))}
            </li>
        );
    }
}

export default Book;

Solution

  • getAuthors is a class property. This is a proposed evolution, you can have Babel transpile it by using babel-plugin-transform-class-properties