Why external javascript file not working Rails 6?

Viewed 2788

I'm using Ruby on Rails 6 and I'm trying to move custom javascript file to an external file and it's not working. Javascript code is working if I move the code to erb file. Can you help me please ?

This is index.html.erb (app/views/home/index.html.erb)

<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>
<i class="fab fa-twitter"></i>
<i class="fas fa-home"> </i>

<button id="target" value="submit">Submit</button>

<script>
 // this code is working if i put inside .erb file
 /* $( "#target" ).click(function() {alert( "Testing" );}); */
</script>

This is custom.js (app/javascript/packs/custom.js)

console.log("File loaded");
$( "#target" ).click(function() {
    alert( "Testing" );
});

This is my application.js (app/javascript/packs/application.js)

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require('jquery')
require("packs/custom")

This is my environment.js (app/config/webpack/environment.js)

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide',
    new webpack.ProvidePlugin({
        $: 'jquery/src/jquery',
        jQuery: 'jquery/src/jquery'
    })
)

module.exports = environment
3 Answers

Make sure you run your application in development mode:

rails s -e development

If you run it in production mode, make sure you run this before:

RAILS_ENV=production bundle exec rails webpacker:compile

You can also opt to include the .js file only for a specific view. In index.html.erb you can add:

<%= javascript_include_tag "custom", "data-turbolinks-track" => true  %>

You should replace this. <%= javascript_pack_tag "custom", "data-turbolinks-track" => true %>

this will look to your pack, while include will look to your assets folder.

I know it's late but I had the exact same problem and I fixed it adding:

jQuery(() => {
   //Your js goes here
})

or the equivalent $(document).ready(() =>{})

This is because of Turbolinks incompatiblity. There are other workarounds but for now this made the trick in my case.

Related