8

With the arrival of Webpacker to Ruby On Rails, I can't find a way to use my JavaScript functions.

I have a file called app-globals.js with a function to test:

function alerts() {
  alert("TEST")
}

Then I want to use it in one of my views:

<% = button_tag 'Button', type: 'button', onClick: 'alerts ()'%>

But when I press the button, this error is shown in the browser console:

ReferenceError: alerts is not defined

  1. I placed the app-globals.js file in "app/javascript" and in "app/ javascript/packs/application.js" I placed require ("app-globals").

  2. I moved app-globals.js to "app/javascript/packs" and removed the require ("app-globals") from application.js.

With either case, an error still appears.

Syntle
  • 5,168
  • 3
  • 13
  • 34
Johan Donado B.
  • 223
  • 3
  • 10
  • Does this answer your question? [Rails 5/6: How to include JS functions with webpacker?](https://stackoverflow.com/questions/54501241/rails-5-6-how-to-include-js-functions-with-webpacker) – Michael Chaney Jun 08 '20 at 16:57

1 Answers1

8

There is a workaround, though. You can:

change the function signatures from:

function myFunction() { ... }

to:

window.myFunction = function() { ... }

So in your code we can do like below :-

app/javascript/packs/app-globals.js

window.alerts = function() {
    alert ("TEST");
}

and then require this file to application.js :-

app/javascript/packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()

require("@rails/activestorage").start()
require("channels")
require("jquery")

import $ from 'jquery'
window.jQuery = $;
window.$ = $;


require("packs/app-globals") ## require your file
Johan Donado B.
  • 223
  • 3
  • 10
code_aks
  • 1,972
  • 1
  • 12
  • 28
  • This is not the correct way to do it. The question is a dup, please see https://stackoverflow.com/questions/54501241/rails-5-6-how-to-include-js-functions-with-webpacker/56549843 and my correct answer there. – Michael Chaney Jun 08 '20 at 16:53
  • Note that part of this answer is copied/pasted from the wrong answer at the earlier question. – Michael Chaney Jun 08 '20 at 16:59
  • This is not the wrong answer, I have implemented the same in my Rails 6 project which is successfully worked. Currently I am also working with Rails 6 app. You can see this comment **Maybe all above works – Alexander Gorg** he is also pinting the same thing. – code_aks Jun 08 '20 at 18:05
  • This answer is not correct. Yes, it works, but it's not the correct way to use the new javascript packs. See my correct answer at the link above. – Michael Chaney Jun 08 '20 at 19:28
  • This worked for me but only for one function. When I tried to do multiple functions (i.e. window.showNum() window.showAlph() window.myFunction() ) - it totally stopped working. – developer01 Sep 07 '20 at 22:07