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
I placed the app-globals.js
file in "app/javascript"
and in "app/ javascript/packs/application.js"
I placed require ("app-globals").
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.
The directory structure for JavaScript has changed to the app/javascript/packs/ folder. In that folder you will find the application. js file, which is just like the application. css file.
A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With