Skip to content

Instantly share code, notes, and snippets.

@tvandervossen
Last active May 5, 2018 09:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvandervossen/9b76d7437961650240d14d9f6ecc4183 to your computer and use it in GitHub Desktop.
Save tvandervossen/9b76d7437961650240d14d9f6ecc4183 to your computer and use it in GitHub Desktop.
Quick guide for people who want to add stimulus.js to a Rails 5.2 app but who haven’t used much Modern JavaScript

How to add stimulus.js to a Rails 5.2 app

This might also work or Rails 5.1, but I haven’t tried that yet.

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

Then run:

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

And finally add the following to the head element in your layout (app/views/layouts/application.html.erb in most cases):

<%= javascript_pack_tag 'application' %>

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

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

console.log('Hello World from Webpacker')

Deployment is likely to fail with an 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)

For more, see https://github.com/rails/webpacker and https://stimulusjs.org

@tvandervossen
Copy link
Author

One more thing, you’re going to want to tell your editor to ignore node_modules as well.

@tvandervossen
Copy link
Author

If your CI test run fails after doing this, then you might need to run yarn install as part of your setup to make sure all the npm packages on your CI server are up-to-date.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment