1

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:

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

    s = 40

There error in webpack is as follows:

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!

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.

Here's my .babelrc

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

And here's my 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?

Eamorr
  • 9,872
  • 34
  • 125
  • 209
  • are you sure the @observable is correctly supported? – Loufs Jan 11 '18 at 15:05
  • @Anselm thanks so much. Yes, everything compiles fine when I remove the `let s = 40` line – Eamorr Jan 11 '18 at 15:07
  • 1
    I may have found my answer... https://stackoverflow.com/a/37840719/395974 – Eamorr Jan 11 '18 at 15:08
  • 1
    the order of presets is wrong, have es2015 as the top one - not react. it needs to compile down to that from right to left. also, class properties transform plugin missing, though it may be covered by stage-1 as it's now stage-3 – Dimitar Christoff Jan 11 '18 at 15:09
  • 1
    You also may have a look at https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes – Gabriel Bleu Jan 11 '18 at 15:10

1 Answers1

0

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.

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:

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();
  }
}
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99