Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack module build failed unexpected token (rails react build)

I working on a react/rails build and working through using webpack and babel for the first time. I'm using two files and getting the error:

ERROR in ./app/assets/frontend/main.jsx
Module build failed:
SyntaxError: /Users/cls/GitHub/rails_react/app/assets/frontend/main.jsx: Unexpected token (6:6)

Line 6 is: <Greet />

This is the main.jsx file

import Greet from './greet';

class Main extends React.Component {
    render() {
        return (
            <Greet />
        );
    }
}
let documentReady = () => {
    React.render(
        <Main />,
        document.getElementById('react')
    );
};
$(documentReady);

This is the greet.jsx file:

export default class Greet extends React.Component {
    render() {
        return <h2>Hello There</h2>
    }
}

This 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" }
    ]
  }
};

I don't have a babelrc file?

like image 250
chrissavage Avatar asked Jan 26 '16 21:01

chrissavage


2 Answers

First make sure to install react, babble and other dependencies in your solution using

   npm install react --save 

then in the web pack config file please include presets in the query similar to below:

   module.exports = {
entry: 'main.jsx',
output: {
    // Output the bundled file.
    path: './src',
    // Use the name specified in the entry key as name for the bundle file.
    filename: 'bundle.js'
},
module: {
    loaders: [{
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
            presets: ['react']
        }
    }]
},
externals: {
    // Don't bundle the 'react' npm package with the component.
    'react': 'React'
},
resolve: {
    // Include empty string '' to resolve files by their explicit extension
    // (e.g. require('./somefile.ext')).
    // Include '.js', '.jsx' to resolve files by these implicit extensions
    // (e.g. require('underscore')).
    extensions: ['', '.js', '.jsx']
}
}; 
like image 157
Milad Rezazadeh Avatar answered Sep 19 '22 08:09

Milad Rezazadeh


So with all the feedback given I was able to figure it out. Thank you to everyone who answered.

Here is what I needed to do:

npm install babel-preset-es2015

npm install babel-preset-react

And create a .babelrc file (thank you to azium and Kreozot)

`{
  "presets": [
    "react",
    "es2015"
  ]
}`
like image 32
chrissavage Avatar answered Sep 21 '22 08:09

chrissavage