语法错误React.js

时间:2017-02-03 14:35:20

标签: javascript reactjs react-router

我已经完成了React / Elixir“learnphoenix.io”教程,我在路线和视图部分。我有编译错误

ERROR in ./app/index.js
Module build failed: SyntaxError: Unexpected token (6:22)

  4 | import { default as Home } from   "./components/Home"
  5 | import { default as Settings } from   "./components/Settings"
> 6 | const App =   props   => (<div>{props.children}</div>)
    |                         ^
  7 | ReactDOM.render(
  8 |       <Router history={hashHistory}>
  9 |               <Route path="/" component={App}>

 @ multi main
webpack: bundle is now VALID.

我是React的新手,所以我不太了解。

EDIT1: 有webpack.config.js:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'eval',
  entry: [
    'webpack-dev-server/client?http://localhost:3000',
    './app/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'babel']
        },
        include: path.join(__dirname, 'app')
      }
    ]
  },
  resolve: {
    extensions: [ '', '.js' ]
  }
}

app / index.js:

import React from "react"
import ReactDOM from "react-dom"
import { Router, Route, IndexRoute, hashHistory }   from "react-router"
import { default as Home } from "./components/Home"
import { default as Settings } from "./components/Settings"
const   App =   props   => (<div>{props.children}</div>)
ReactDom.render(
        <Router history={hashHistory}>
                <Route path="/" component={App}>
                        <IndexRoute component={Home}/>
                        <Route path="settings"  component={Settings}/>
                </Route>
        </Router>,
        document.getElementById("root")
)

app / Home / index.js:

import React from "react"

export class Home extends React.Component {
  render() {
    return (<div>Home component</div>)
  }
}

export default Home

2 个答案:

答案 0 :(得分:1)

这是正确的jsx ES6语法,但它看起来像保存为.js。

你需要在构建过程中有一个转换步骤,可能是使用Babel

答案 1 :(得分:1)

将此添加到预设中:

['es2015','stage-0','react']

这没有错

const App =   props   => (<div>{props.children}</div>)

它应该转化为:

"use strict";

var App = function App(props) {
    return React.createElement(
        "div",
        null,
        props.children
    );
};

但是您缺少react转录器部分。如果我没有使用反应标记,我欺骗了错误in Babel

评估预设:es2015,es2016,stage-1 Line Wrap Minify(Babili)Babel 6.22.1

repl: Unexpected token (1:26)
> 1 |     const App = props => (<div>{props.children}</div>)
    |                           ^

这称为胖箭头语法,道具是无状态函数的参数。您正在为该功能设置名称App,并且您将返回JSX。

当你没有反应时,JSX部分无法被编译并从那里出现错误。