./app/main.js中的错误模块构建失败:SyntaxError:意外的令牌(10:18)

时间:2017-01-12 12:22:13

标签: javascript reactjs

当我使用' webpack' ,下面的错误......

./app/main.js中的错误 模块构建失败:SyntaxError:意外的令牌(10:18)

   8 | 
   9 | function main(){
> 10 |   ReactDOM.render(<Hello />, document.getElementById('app'));
     |                   ^
  11 | }
  12 | main();
  13 | 

component.jsx

<div><i>   import React from 'react';
     export default class Hello extends React.Component {
       render() {
       return (<h1>Hello World---component.jsx</h1>)
      }
  }</i></div>

main.js

 import React from 'react';
  import ReactDOM from 'react-dom';
  import Hello from './component.jsx';

   function main(){
    ReactDOM.render(<Hello />, document.getElementById('app'));
  }
  main();

的package.json

{
  "name": "enviromentproject",
  "version": "1.0.0",
  "description": "一个用来做环境搭建的项目测试",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
  },
  "author": "jkwu",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-runtime": "^6.20.0",
    "css-loader": "^0.26.1",
    "style-loader": "^0.13.1",
    "vue-hot-reload-api": "^2.0.7",
    "vue-html-loader": "^1.2.3",
    "vue-style-loader": "^1.0.0",
    "webpack": "^1.14.0"
  },
  "dependencies": {
    "hexo-deployer-git": "^0.2.0",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "webpack-dev-server": "^1.16.2"
  }
}

2 个答案:

答案 0 :(得分:1)

首先,你的component.jsx不应该在html标签内

简单写

import React from 'react';
     export default class Hello extends React.Component {
       render() {
       return (<h1>Hello World---component.jsx</h1>)
      }
  }

其次,更重要的是确保在webpack配置中将babel指定为jsx的加载器

module : {
    loaders : [
      {
        test : /\.jsx?/,
        exclude : /node_modules/,
        loader : 'babel'
      }
    ]
  }

此外,它不会导致问题,但您不需要在函数内调用ReactDOM.render()

class Hello extends React.Component {
       render() {
       return (<h1>Hello World---component.jsx</h1>)
      }
  }

    ReactDOM.render(<Hello />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>

答案 1 :(得分:0)

添加&#34; babel-preset-react&#34;

npm install babel-preset-react 并添加&#34;预设&#34; webpack.config.js中的babel-loader选项

(或者您可以将其添加到.babelrc或package.js:http://babeljs.io/docs/usage/babelrc/

以下是webpack.config.js的示例:

{ 
    test: /\.jsx?$/,         // Match both .js and .jsx files
    exclude: /node_modules/, 
    loader: "babel", 
    query:
    {
        presets:['react']
    }
}

然后:npm install react-dom --save 在main.js 从&#39; react-dom&#39;;

导入{render}

使用此渲染