由于某些原因,我的代码无法编译。奇怪的是,当我使用浏览器中的解释器时,它将起作用。

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


我认为我一定在做一些愚蠢的事情,例如缺少一些在浏览器中运行的内容,这很奇怪。这会掩盖一些错误,因为它被解释为与运行前已编译的相对吗?

最佳答案

根据注释,您可能缺少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体积小且承诺/ A +
  兼容性。
  
  要与webpack一起使用,请在条目配置中添加此软件包
  应用程序入口点之前的选项:
  
  entry: ['whatwg-fetch', ...]
  
  对于Babel和ES2015 +,请确保
  导入文件(在您的react-components中):
  
  import 'whatwg-fetch'


另外,查看您的代码(这在间距方面与常规javascript样式指南有所不同),我会考虑在您的环境中启动eslint并在其中运行以针对此类错误提供更好的反馈。如果启用了eslint,则尝试这种操作而不先导入fetch is undefined就会得到fetch

来自我的另一笔个人笔记,请尝试仅在文件中导入whatwg-fetch,然后再篡改Webpack配置。您可能不需要将其添加为条目。

祝你好运!

关于node.js - 无法使用Webpack编译React代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44353985/

10-16 02:57