Webpack不理解React的语法

时间:2016-03-28 17:10:30

标签: reactjs webpack

我正在学习React和Webpack。现在我编写了一个显示名称的组件; - )

const app = document.getElementById('app');

class World extends React.Component {
  constructor(props) {
    super(props);
    this.name = 'Tomek';

    this.callByName = this.callByName.bind(this); /* Or bind directly when calling */
  }

  callByName() {
    alert(this.name);
  }

  render() {
    return (
      <div>
        <h2>Hello, {this.name}</h2>
        <button onClick={this.callByName}>Alert</button>
      </div>
    )
  }
}

ReactDOM.render(<World />, app);

我用React和ReactDOM导入它:

import React from 'react';
import ReactDOM from 'react-dom';

import './components/posts/index.js';

我使用Webpack来处理我的JS:

module.exports = {
    entry: [
        './_babel/index.js'
    ],
    output: {
        path: __dirname + '/_js',
        filename: 'index.js'
    },
    module: {
        loaders: [
            { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
        ]
    }
};

不幸的是,当我运行webpack时,我得到了

ERROR in ./_babel/components/posts/index.js
Module build failed: SyntaxError: /Users/tomek/Sites/wordpress/wp-content/themes/Devoid/_babel/components/posts/index.js: Unexpected token (17:6)
  render() {
    return (
      <div>
        <h2>Hello, {this.name}</h2>
        <button onClick={this.callByName}>Alert</button>
      </div>

可能我只是忘了什么,但我似乎无法找到什么。

1 个答案:

答案 0 :(得分:4)

您需要将react loader添加到webpack.config.js。我还建议添加ES2015装载机。试试这个:

module.exports = {
    entry: [
        './_babel/index.js'
    ],
    output: {
        path: __dirname + '/_js',
        filename: 'index.js'
    },
    module: {
      loaders: [
        {
          test: /\.js$/,
          loader: 'babel-loader',
          exclude: /node_modules/,
          query: {presets: ['es2015']}
        },
        {
          test: /\.jsx$/,
          loader:'babel-loader',
          query: {presets: ['es2015', 'react']}
        }
      ]
    }
};