无法编译语法错误:reactjs

时间:2017-10-26 11:14:33

标签: node.js reactjs babel

Failed to compile

./src/components/TodoBox.js
Syntax error: Unexpected token (16:6)

  14 |       e.preventDefault();
  15 |     }
> 16 |       <div className="TodoBox">
     |       ^
  17 |         <form onSubmit={this.onSubmit }>
  18 |           <input
  19 |             type="text" value={this.state.todoText}

This error occurred during the build time and cannot be dismissed.

我有这个错误,我使用npm install -g create-react-app创建了项目 假设create-react-app构建了所有依赖的项目,如webpack和babel。我在其他人看到发布错误语法的问题是为了babel,不是吗?我安装了这个版本的babel

/var/www/html/todo-list$ sudo  npm install --save-dev babel-cli
todo-list@0.1.0 /var/www/html/todo-list
└─good@good:┬ babel-cli@6.26.0 
  ├── babel-core@6.26.0 
  ├─┬ babel-polyfill@6.26.0 
  │ ├── core-js@2.5.1 
  │ └── regenerator-runtime@0.10.5 
  ├── fs-readdir-recursive@1.0.0 
  ├── output-file-sync@1.1.2 
  ├── source-map@0.5.7 
  └─┬ v8flags@2.1.1 

todobox.js

import React, { Component } from 'react';
import '../styles/TodoBox.css';

class TodoBox extends Component {
  constructor() {
    super();
      this.state = {
        todoText: ''
      }
    }
    onSubmit(e){
      console.log(e);
      e.preventDefault();
    }
    render() {
      return (    
      <div className="TodoBox">
        <form onSubmit={this.onSubmit }>
          <input
            type="text" value={this.state.todoText}
            onChange={(e) => {this.setState({todoText: e.target.value})}}/>
            <input type="submit" value="Agregar"/>
        </form>
      </div>
    );
  }
}

export default TodoBox;

的package.json

{
  "name": "todo-list",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-scripts": "1.0.14"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0"
  }
}

1 个答案:

答案 0 :(得分:1)

看起来Babel无法理解JSX语法。

检查您是否安装了babel-preset-react软件包,并且已将react添加到{"babel":{"presets":[]}} package.json内的.babelrc列表或package.json文件中的预设列表中。

你的babel预设配置应该是这样的(在{ "devDependencies": { "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1" }, "babel": { "presets": [ "es2015", "react" ] } } 的情况下,我删除了不相关的行):

>>> import os, glob
>>> os.system("tree ./matcher")
matcher
├── matcher2.py
├── matcher.cpp
├── matcher.py
└── question.md

0 directories, 4 files
0
>>> glob.glob("matcher/*.py")
['matcher/matcher2.py', 'matcher/matcher.py']