React.js SyntaxError:意外的令牌<

时间:2016-05-11 16:00:49

标签: javascript node.js reactjs

我在react.js中真的很新。我在Webstorm中发展。

我有这个错误,我没有成功解决它,看起来反应无法识别,但我尝试安装任何npm反应包,仍然无法正常工作..

  • SyntaxError:意外的标记<

这是我的代码:

index.jsx:

    /** @jsx React.DOM */
var React = require('react');
var ReactDOMServer = require('react-dom');
var DefaultLayout = require('./layout/Master');
//var element = React.createElement('div', null, 'Hello World!');
//console.log(ReactDOMServer.renderToString(element));

var CommentBox = ReactDOMServer.createClass({
    render: function() {
        return (
            <div>
                <h1>aslkdjaslkdj</h1>
            </div>
            //React.createElement('div', null, 'Hello World!')

        );
    }
});

module.exports = CommentBox;`var express = require('express');

index.js:

    var express = require('express');
var router = express.Router();

var request = require('request');

router.get('/', function (req, res) {
    //res.send("<h1> asdasasd </h1>");
    res.render('index', {});
});
module.exports = router;

app.js:

var app = express();

var routes = require('./routes/index');
var path = require('path');

app.use('/', routes);

app.set('port', process.env.PORT || '5000');

// view engine setup
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine());

app.use('/', routes);

module.exports = app;
var server = app.listen(app.get('port'), function(){
    console.log("app started");

});`

package.json:

    {
  "name": "nodewithreactwithjsx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Almog.h",
  "license": "ISC",
  "dependencies": {
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babel-register": "latest",
    "express": "^4.13.4",
    "express-react-views": "latest",
    "react": "^15.0.2",
    "react-dom": "^15.0.2"
  },
  "devDependencies": {
    "babel-core": "^6.8.0",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "react": "^15.0.2",
    "react-dom": "^15.0.2",
    "webpack": "^1.13.0"
  }
}

1 个答案:

答案 0 :(得分:1)

我认为这是因为您的代码具有JSX - 即HTML inside JavaScript

CommentBox部分

要让JavaScript运行这个,你需要使用像Babel这样的转换器 - 这会变成如下声明:

<div className="apples">hello</div>

React.createElement('div', {className:'apples'}, 'hello')

Javascript引擎(如Chrome中的V8)无法本机运行JSX - 它们需要首先进行转换。我不知道如何在BabStorm中使用像babel这样的东西。