Skip to content

Instantly share code, notes, and snippets.

@tvandervossen
Created April 11, 2018 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvandervossen/aa3ea55f71e62e95db778c3591f2f991 to your computer and use it in GitHub Desktop.
Save tvandervossen/aa3ea55f71e62e95db778c3591f2f991 to your computer and use it in GitHub Desktop.
Quick guide to add stimulus.js to a Rails 5.2 app if you haven’t used much Modern ™ JavaScript before

Add stimulus.js to a Rails 5.2 app

According to https://github.com/rails/webpacker you should:

Add the webpacker gem to your Gemfile:

# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker'

Then run (assuming you’re on macOS and using Homebrew):

$ brew install yarn

And run:

$ bundle exec rails webpacker:install
$ bundle exec rails webpacker:install:stimulus

And add the following to your head:

<%= javascript_pack_tag 'application' %>

You might want to remove the following line from app/javascript/packs/application.js:

console.log('Hello World from Webpacker')

There’s should be a demo stimulus controller on app/javascripts/controllers/hello_controller.js which you might use to see if everything works as expected.

Deployment is likely to fail with a “Uglifier::Error: Unexpected token: punc ({). To use ES6 syntax, harmony mode must be enabled with Uglifier.new(:harmony => true).” error message. To fix this, change “config.assets.js_compressor = :uglifier” in config/environments/production.rb to:

config.assets.js_compressor = Uglifier.new(harmony: true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment