没有用webpack编译的反应代码

时间:2017-06-04 12:15:50

标签: node.js reactjs webpack babel

我的代码由于某种原因不会编译。奇怪的是,当我使用浏览器解释器时它会起作用。

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>

反应代码:

var Cookies = require('cookies');

var cookieParser = require('cookie-parser');


var name = document.getElementById('name').innerHTML;
//var name = req.user.name;

  var start = false;
  var Assets = React.createClass({
    getInitialState: function(){
      return({
        assets: [],
        secondsElapsed: 0
      });
    },
    tick: function() {
      //this.setState({secondsElapsed: this.state.secondsElapsed + 1});
      if(start === true){
        console.log(name);

        var myHeaders = new Headers();

        var token = new Cookies(req,res).get('access_token');

        myHeaders.append('acess_token', token);

        var myInit = { method: 'GET',
               headers: myHeaders};

        fetch('/api/user/all/?name='+name, myInit).then(function(data){
          return data.json();
        }).then( json => {
          this.setState({
              assets: json
            });
        });
    }
    },
    componentDidMount: function() {
      this.interval = setInterval(this.tick, 1000);
    },
    componentWillUnmount: function() {
      clearInterval(this.interval);
    },
    render: function(){
      var assets = this.state.assets;
      assets = assets.map(function(asseti,index){
        return(
          asseti.map(function(asset, index){
            return(
              <li key={index}>
                        <span className={asset.active}></span>
                        <span>{asset.name}</span>
                        <span >{asset.description}</span>
                        <span>{asset.location.coordinates[0]}{asset.location.coordinates[1]}</span>
              </li>
            )
          })
        )
      });
      return(
        <div>
          <form onSubmit={this.handleSubmit}>
            <input type="submit" value="Find assets" />
          </form>
          {assets}
        </div>
      );
    },
    handleSubmit: function(e){
      e.preventDefault();
      start = true;
    //  name = this.refs.name.value;

      fetch('/api/user/all/?name='+name).then(function(data){
        return data.json();
      }).then( json => {
        this.setState({
          assets: json
        });
      });
    }
  });

ReactDOM.render(<Assets />, document.getElementById('assets'));

Webpack.config.js:

var path = require('path');

module.exports = {
    entry: path.resolve(__dirname, 'puplic') + '\\js\\baseReact.js',
    output: {
        path: path.resolve(__dirname, 'dist') + '/app',
        filename: 'bundle.js',
        publicPath: '/app/'
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                include: path.resolve(__dirname, 'public/js'),
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015', 'stage-0']
                }
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            }
        ]
    },
    devServer: {
 historyApiFallback: true
}
};

错误:

ERROR in ./puplic/js/baseReact.js                                                                
Module parse failed: C:\Users\test\Documents\GPSTracker\puplic\js\baseReact.js Unexpected token (
53:14)                                                                                           
You may need an appropriate loader to handle this file type.                                     
|           asseti.map(function(asset, index){                                                   
|             return(                                                                            
|               <li key={index}>                                                                 
|                         <span className={asset.active}></span>                                 
|                         <span>{asset.name}</span>                                              

我认为我必须做一些愚蠢的事情,因为它在浏览器中运行时遗漏了一些奇怪的东西。这是否会掩盖某些错误,因为它被解释为与之前编译相反的错误?

1 个答案:

答案 0 :(得分:1)

根据评论,您可能会错过fetch导入。获取时间为not readily available in all browsers

npm包whatwg-fetch具体提到了如何让fetch在支持webpack的环境中工作。

  

安装

     

npm install whatwg-fetch --save

     

     

bower install fetch

     

您还需要旧版浏览器的Promise polyfill。我们推荐   taylorhakes / promise-polyfill因其小尺寸和Promises / A +   兼容性。

     

要与webpack一起使用,请在条目配置中添加此包   申请入境点之前的选项:

     

entry: ['whatwg-fetch', ...]

     

对于Babel和ES2015 +,请务必   导入文件(在您的react-components中):

     

import 'whatwg-fetch'

此外,查看您的代码,这与常规的javascript样式指南在间距方面略有不同,我会考虑在您的环境中启动并运行eslint,以便更好地反馈错误,例如这些。如果您启用了eslint,那么只要您尝试这样的内容,就可以在不首先导入fetch is undefined的情况下获得fetch

我的另一个个人提示,在篡改您的webpack配置之前,尝试在您的文件中导入whatwg-fetch。您可能不需要将其添加为条目。

祝你好运!