I’ve built a few projects in Rails 6 that don’t have a front end framework and aren’t using webpack. In these projects, I’ve wanted to include a couple of small Javascript features. In one case, it was just a little bit of plain DOM manipulation in Javascript. In another case though, I needed my Javascript to take an argument in Ruby, process that data, and output it in the DOM. I couldn’t figure out why the Javascript in my pack files wasn’t rendering.

As it turns out, the pack files and webpack weren’t what I needed. I needed to use Sprockets to access that Javascript. The post How to write Javascript in Rails 6 | Webpacker, Yarn and Sprockets by Younes SERRAJ helped me to get there. Here is how I did it.

Create a /javascripts directory where Sprockets (not webpack) can find it:

app
| assets
  | stylesheets
  | javascripts   <-- here

Add this new directory to the app/assets/config/manifest.js file so it will be compiled:

/* app/assets/config/manifest.js */

//= link_tree ../images
//= link_directory ../stylesheets .css
//= link_directory ../javascripts .js  <-- here

Save your javascript file with all of your code in it there

// app/assets/javascripts/users.js

function sayHelloToUser(userName){
  alert(`Hello, ${userName}!`)
};

Load the contents of your Javascript file into the bottom of your erb file by using the javascript_include_tag (not the Webpacker javascript_pack_tag). Include a <script> tag below that. Call the Javascript function from inside that script block, passing in the Ruby data as an argument:

<!-- app/views/users/show.html.erb -->

<h1><%= @user.name %>'s Page</h1>

...

<%= javascript_include_tag 'users'%>

<script type="text/javascript">
  sayHelloToUser(<%= @user.name %>);
</script>

And voila! That did the trick for me. Now that I have my Javascript working and deployed, I can go back to refactor for use with webpack later. In the meantime, my features are deployed and my app is working as expected.