Bagus Trihatmaja
Bagus Trihatmaja

Reputation: 865

Webpack unexpected token error

I am using Rails 5 with react with webpack 2.1.0-beta.7. With gem 'react-rails', '~> 1.7.0'.

However I got this error every time I try to run webpack.

Hash: 3aea6d8a27453c0be041
Version: webpack 2.1.0-beta.7
Time: 507ms
    + 1 hidden modules

ERROR in ./app/assets/frontend/main.jsx
Module build failed: SyntaxError: /mnt/data/Projects/kasih.in-dev/kasih.in/app/assets/frontend/main.jsx: Unexpected token (5:8)
  3 |   render() {
  4 |     return (
> 5 |         <h1>Hello world</h1>
    |         ^
  6 |     );
  7 |   }
  8 | }
    at Parser.pp.raise (/mnt/data/Projects/kasih.in-dev/kasih.in/node_modules/babylon/lib/parser/location.js:22:13)
    at Parser.pp.unexpected (/mnt/data/Projects/kasih.in-dev/kasih.in/node_modules/babylon/lib/parser/util.js:89:8)

Here is my webpack config:

module.exports = {
    entry: "./app/assets/frontend/main.jsx",
    output: {
        path: __dirname + "/app/assets/javascripts",
        filename: "bundle.js"
    },
    resolve: {
      extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            { test: /\.jsx$/, loader: "babel-loader" }
        ]
    }
};

In case you need it, here is my jsx file:

class Main extends React.Component {
  render() {
    return (
        <h1>Hello world</h1>
    );
  }
}

let documentReady = () => {
  React.render{
    <Main />,
    document.getElementById('main');
  };
};

$(documentReady);

I am wondering what the cause of this error and how to fix it?

Upvotes: 1

Views: 523

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77522

You need install several packages, react and es2015,

npm i --save-dev babel-preset-react babel-preset-es2015

and then add these presets to your webpack config

loaders: [{ 
  test: /\.jsx$/, 
  loader: "babel-loader", 
  query: { 
    presets: ['es2015', 'react']  
  } 
}]

Upvotes: 1

Related Questions