2016-03-28 21 views
1

我正在學習React和Webpack。現在我已經寫了一個顯示名稱;-)Webpack不理解React的語法

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); 

我導入反應並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> 

顯然,我只是忘了一些東西,但我似乎無法找到什麼。

+0

哪個版本的babel .. 5或6? – azium

回答

4

您需要將反應加載器添加到您的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']} 
     } 
     ] 
    } 
}; 
+0

你是完全正確的!我忘了指定Babel預設;-)謝謝!儘管我使用了'.babelrc'文件。 –