I\'m currently trying Rails 6.0.0.rc1 which seems to have moved the default javascript
folder from app/assets/javascript
to app/javascript
Get better-organized code and avoid multiple javascript_pack_tags in your application.html.erb file with this approach:
example.js
javascript file to app/javascript/packs
.require("packs/example")
to your application.js
file.I would have liked to add a comment to Asim Hashmi's correct answer. But I don't have enough reputation, so I'll add my suggestion as an answer instead.
It isn't necessary to include the ".js" extension inside of the require.
I know this question has already answered. But I want to contribute my answer too. In rails 6 by default it used webpack to compile js and css.
By using Require ( ) or import you can easily include js in the application
Now refresh the page, Surely it works.
For further doubts please refer my blog. It will helpful Rails 6 - Webpacker
You need to do the following steps to add custom javascript file to rails 6 (webpacker)
1.Create your custom file named custom.js
in app/javascript/packs
directory.
For testing purpose, write any console.log
in it.
// app/javascript/packs/custom.js
console.log("custom js file loaded")
2. Go to your application.html.erb
and add the following line at the end of your <head></head>
<%= javascript_pack_tag 'custom', 'data-turbolinks-track': 'reload' %>
3. Now execute rake assets:precompile
This will pack your javascript code (including our custom file we just added)
Now reload your page and you should see the message
custom js file loaded
in your browser console
Hope it helps :)
My custom js has functions which will be called by embedded javascript of serveral html pages. Following snippet works in Rails6, compiled by webpacker:
say_hello = function(a_text){
console.log("HELLO "+ a_text);
}
<%= javascript_pack_tag 'my_functions' %>
<!-- html here -->
<script>
$(document).ready(function(){
say_hello('ABer')
});
</script>
Note : This line is inside html body, not in head
<script src="/packs/js/my_functions-1db66368ebbd2fe31abd.js"></script>