使用webpack进行编译时出现反应错误

时间:2016-07-23 10:29:16

标签: reactjs webpack

我有以下内容:

import React from 'react';  
import Router from 'react-router';  
import { DefaultRoute, Link, Route, RouteHandler } from 'react-router';

import LoginHandler from './components/Login.js';

let App = React.createClass({  
  render() {
    return (
      <div className="nav">
        <Link to="app">Home</Link>
        <Link to="login">Login</Link>

        {/* this is the importTant part */}
        <RouteHandler/>
      </div>
    );
  }
});

let routes = (  
  <Route name="app" path="/" handler={App}>
    <Route name="login" path="/login" handler={LoginHandler}/>
  </Route>
);

Router.run(routes, function (Handler) {  
  React.render(<Handler/>, document.body);
});

当我跑步&#34; npm start&#34;基于我的配置:

var webpack = require('webpack');


module.exports = {  
    entry: [
      'webpack/hot/only-dev-server',
      "./js/app.js"
    ],
    output: {
        path: __dirname + '/build',
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.js?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ },
            { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
            { test: /\.css$/, loader: "style!css" }
        ]
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin()
    ]

};

我收到以下错误:

./js/app.js
Module build failed: SyntaxError: /Users/alessandrosantese/Documents/PROJECTS/react-router-16/js/app.js: Unexpected token (10:6)
   8 |   render() {
   9 |     return (
> 10 |       <div className="nav">
     |       ^
  11 |         <Link to="app">Home</Link>
  12 |         <Link to="login">Login</Link>
  13 | 

2 个答案:

答案 0 :(得分:2)

我认为您希望.js.jsx同时运行react-hotbabel,但您的模式与.j.js匹配(我认为您假设?是通配符,但在正则表达式中,它表示“匹配前面的表达式0或1次”)。

试试这个:

test: /\.jsx?$/

答案 1 :(得分:1)

我建议你做两个改变。

首先:

在包含function DataBase(){ this.getData = function(){ var data = [1, 2, 3, 4, 5]; return Promise.resolve(data); } } function Data(d){ this.first = null; that = this; this.getFirst = function(){ return this.first; } this.initialize = function(){ dataBase = new DataBase(); dataBase.getData().then( function(theArray){ console.log(theArray); //works fine that.first = theArray[0]; //doesn't work because promise is asyncronous }) } } d = new Data(); d.initialize(); result = d.getFirst(); console.log(result)// is null react-hot的网址中,您需要转换jsx。所以将测试更改为

babel loader

检查{ test: /\.jsx?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }, .js

<强>第二

而不是.jsx使用React.render()

ReactDOM.render()