简体   繁体   中英

Rails Webpacker and stage-2 class transform properties not working

I'm trying out Webpacker on a new Rails application to get familiar with it and I can't get it to compile my javascript code.

Here's the code:

import React, { Component, PropTypes } from 'react'
import DayPicker, { DateUtils } from 'react-day-picker'
import 'react-day-picker/lib/style.css'

export default class Example extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectedDays: []
    }
  }

  handleDayClick = (day, selected) => {
    console.log(day)
  }

  render() {
    return (
      <p>Test</p>
    )
  }
}

20:05:21 hot.1  | ERROR in ./app/javascript/packs/components/example/example.jsx
20:05:21 hot.1  | Module build failed: SyntaxError: Missing class properties transform.
20:05:21 hot.1  |
20:05:21 hot.1  |   11 |   }
20:05:21 hot.1  |   12 |
20:05:21 hot.1  | > 13 |   handleDayClick = (day, selected) => {
20:05:21 hot.1  |      |   ^

This is on a brand new Rails app using the latest Webpacker gem from github.

My .babelrc :

{
  "presets": ["env", "es2015", "react", "stage-2"]
}

My devDependencies are:

"devDependencies": {
  "babel-preset-es2015": "^6.24.0",
  "babel-preset-stage-2": "^6.22.0",
  "webpack-dev-server": "^2.4.2"
}

According to this Babel REPL link, this should be working. https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-2&targets=&browsers=&builtIns=false&experimental=true&loose=false&spec=false&code=class%20PostInfo%20extends%20React.Component%20%7B%0A%09handleOptionsButtonClick%20%3D%20(e)%20%3D%3E%20%7B%0A%20%20%20%20this.setState(%7BshowOptionsModal%3A%20true%7D)%3B%0A%20%20%7D%0A%7D

Any ideas?

To fix, I had to add the presets to the individual loader files, specifically.

// config/webpack/loaders/babel.js
module.exports = {
  test: /\.js(\.erb)?$/,
  exclude: /node_modules/,
  loader: 'babel-loader',
  options: {
    presets: [
      'es2015',
      'stage-2'
    ]
  }
}

// config/webpack/loaders/react.js
module.exports = {
  test: /\.(js|jsx)?(\.erb)?$/,
  exclude: /node_modules/,
  loader: 'babel-loader',
  options: {
    presets: [
      'es2015',
      'react',
      'stage-2'
    ]
  }
}

Now I can use the nice shorthand arrow class functions.

Your comment was most illuminating: this is a method declaration in a class; there should be no equal sign or fat arrow. This is how it should look:

handleDayClick (day, selected) {
    console.log(day)
}

Take a look at how the constructor and render methods look; that's how all methods in a react component look.

D'oh!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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