1

My code wont compile for some reason. The weird thing is that is will work when I use the in browser interpreter.

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

React code:

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:

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>                                              

I figure I must be doing something dumb like missing something as it runs in browser which is weird. Does that gloss over some errors as it is interpreted as opposed to been compiled before been run?

3
  • Could you try this linted/beautified example? pastebin.com/3tJP8qtM Just to rule those potential issues out. Commented Jun 4, 2017 at 19:16
  • Now it throws the error You may need an appropriate loader to handle this file type. ERROR in ./puplic/js/baseReact.js Module parse failed: C:\Users\test\Documents\GPSTracker\puplic\js\baseReact.js Unexpected token (33:26) You may need an appropriate loader to handle this file type. | fetch('/api/user/all/?name=' + name, myInit).then(function (data) { | return data.json(); | }).then(json) => { | this.setState({assets: json}); | }); Commented Jun 4, 2017 at 19:52
  • have you imported fetch? Is it available for usage? Try mocking/replacing fetch and just return some random value. Commented Jun 4, 2017 at 20:25

1 Answer 1

1

Based on the comments, you may be missing the fetch import. Fetch is not readily available in all browsers.

The npm package whatwg-fetch mentions specifically how to get fetch working in a webpack-enabled environment.

Installation

npm install whatwg-fetch --save

or

bower install fetch.

You will also need a Promise polyfill for older browsers. We recommend taylorhakes/promise-polyfill for its small size and Promises/A+ compatibility.

For use with webpack, add this package in the entry configuration option before your application entry point:

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

For Babel and ES2015+, make sure to import the file (in your react-components):

import 'whatwg-fetch'

Also, looking at your code, which is deviating a tad from regular javascript style guides in terms of spacings, I'd look into getting eslint up and running in your environment for better feedback for errors like these. If you had eslint enabled, you'd get fetch is undefined as soon as you tried something like this without importing fetch first.

Another personal note from me, try just importing whatwg-fetch in your file, before tampering with your webpack config. You may not need to add it as an entry.

Best of luck!

Sign up to request clarification or add additional context in comments.

2 Comments

When you say add the entry do you mean like this:entry: ['whatwg-fetch', path.resolve(__dirname, 'puplic') + '\\js\\baseReact.js']
Although there are many ways to create an entry, that looks like a reasonable one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.