How to require custom JS files in Rails 6

佐手、 提交于 2019-12-01 03:40:34

Get better-organized code and avoid multiple javascript_pack_tags in your application.html.erb file with this approach:

  1. Add your custom example.js javascript file to app/javascript/packs.
  2. Add require("packs/example.js") 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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!