How to require custom JS files in Rails 6

前端 未结 4 660
终归单人心
终归单人心 2020-12-14 07:52

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

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 08:51

    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

    <%= 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 :)

提交回复
热议问题