Stimulus Discourse

Problem integrating with Webpack


#1

I’m trying to use Stimulus in a non-Rails application and I’ve installed Stimulus using NPM and integrated it with Webpack as shown in the Stimulus handbook. I’m also using Yarn to build it all together.

Anyway, I have a very simple Stimulus controller - game_controller.js

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "game" ]
}

And this fails to build with the following error:

WARNING in ./Resources/Javascripts/controllers/game_controller.js 4:17
Module parse failed: Unexpected token (4:17)
You may need an appropriate loader to handle this file type.
| 
| export default class extends Controller {
>   static targets = [ "source" ]
| }
| 
 @ ./Resources/Javascripts/controllers sync \.js$ ./bracket_controller.js
 @ ./Resources/Javascripts/application.js
✨  Done in 1.65s.

Removing the static targets = ["source"] line fixes the build issue. Any ideas on what is going on or if I’m missing something?

Here is my application.js for reference as well.

import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"

const application = Application.start()
const context = require.context("./controllers", true, /\.js$/)
application.load(definitionsFromContext(context))

#2

It sounds like you’re missing the Babel plugin that handles static (class) properties. For example, in my webpack.config.js, I have the following settings for *.js rules:

  {
    test: /\.js/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          '@babel/preset-env'
        ],
        plugins: [
          '@babel/plugin-proposal-class-properties'
        ]
      }
    }
  },

and I made sure I did yarn add @babel/plugin-proposal-class-properties so that’s part of the package.json manifest.

Let me know how that goes!


#3

Thanks, @jaredcwhite. That helped me figure things out.

Here are the dependencies in the package.json.

  "dependencies": {
    "@babel/core": "^7.3.4",
    "@babel/plugin-proposal-class-properties": "^7.3.4",
    "@babel/preset-env": "^7.3.4",
    "babel-loader": "^8.0.5",
    "stimulus": "^1.1.1"
  },
  "devDependencies": {
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3"
  },