react 中bable转换 jsx为 js 出错

大西瓜
  • 21

运行
npm run dev
报错
将jsx转化为js代码报错,求解

 [89] ./app/main.js 638 bytes {0} [built] [failed] [1 error]
    + 75 hidden modules

ERROR in ./app/main.js
Module build failed: SyntaxError: Unexpected token (16:17)

  14 | 
  15 | function main() {
> 16 |     React.render(<Hello/>, document.getElementById('app'));
     |                  ^
  17 | }

配置文件

var path = require('path');
var config = {
    entry: [
        'webpack/hot/dev-server',
        'webpack-dev-server/client?http://localhost:8080',
        path.resolve(__dirname, 'app/main.js')
    ],
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'bundle.js'
    },
    module: {
        loaders: [{
            test: /\.jsx?$/,
            loader: 'babel-loader',
            exclude: /node_modules/
        }]
    }
};

module.exports = config;

package.json文件

{
  "name": "application-name",
  "version": "0.0.1",
  "dependencies": {
    "react": "^15.6.1",
    "webpack": "^3.4.1",
    "webpack-dev-server": "^2.6.1"
  },
  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server"
  },
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1"
  }
}

component.jsx文件

import React from 'react';

export default class Hello extends React.Component {
    render() {
        return <h1>Hello!!!</h1>;
    }
}

main.js

import React from 'react';
import Hello from './component.jsx';

main();

function main() {
    React.render(<Hello/>, document.getElementById('app'));
}
回复
阅读 1.9k
1 个回答
✓ 已被采纳

需要安装babel-preset-reactbabel-preset-es2015

npm install --save-dev babel-preset-react babel-preset-es2015

然后配置一下你的.babelrc,如果没有就新增

{
  "presets": ["react", "es2015"]
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏