简体   繁体   English

React.js和Webpack-为什么不允许var,let,const?

[英]React.js and webpack - why won't it allow var, let, const?

I have a bit of an issue here that I can't get to the bottom of. 我这里有些问题,我无法深入探讨。

Here's a snippet from my Graph.js file: 这是我的Graph.js文件中的片段:

class Graph extends React.Component {
    @observable newTodoTitle = "";

    s = 40

There error in webpack is as follows: webpack中出现错误如下:

ERROR in ./src/components/Graph.js
Module build failed: SyntaxError: Unexpected token (13:6)
2018-01-11T14:56:05.221073500Z 
  11 | 
  12 | 
> 13 |   let s = 40
     |       ^

If I remove the "let", it compiles fine! 如果我删除了“ let”,它可以正常编译!

I'd prefer to keep the var, let, consts, etc. as I want to copy and paste a lot of JavaScript into this file without these errors. 我希望保留var,let,const等,因为我想将很多JavaScript复制并粘贴到此文件中而不会出现这些错误。

Here's my .babelrc 这是我的.babelrc

{
  "presets": [
    "react",
    "es2015",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy"]
}

And here's my webpack.config.js: 这是我的webpack.config.js:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'eval',
  entry: [
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [{
      test: /\.jsx?$/,
      use: ['babel-loader'],
      include: path.join(__dirname, 'src')
    }]
  }
};

Any ideas? 有任何想法吗?

You are trying to use the class-fields proposal (stage 3 currently) which you will need the Class properties transform plugin of babel to support this. 您正在尝试使用class-fields提议(当前为第3阶段),您将需要babelClass属性转换插件来支持此提议。

As you can see in the docs, your syntax is off. 如您在文档中所见,语法已关闭。
There is no need for any variable declaration key word for class fields. 类字段不需要任何变量声明关键字。

Example from the docs : 来自docs的示例:

class Counter extends HTMLElement {
  x = 0;

  clicked() {
    this.x++;
    window.requestAnimationFrame(this.render.bind(this));
  }

  constructor() {
    super();
    this.onclick = this.clicked.bind(this);
  }

  connectedCallback() { this.render(); }

  render() {
    this.textContent = this.x.toString();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM