How to require custom JS files in Rails 6

早过忘川 提交于 2019-12-18 19:03:19

问题


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. The application.js file is now located in app/javascript/packs. Now, I want to add a couple of js files, but for some reason they don't get imported and I can't find any documentation on how this can be done in Rails 6. I tried a couple of things:

  1. Create a new folder custom_js under app/javascript/packs, putting all my js files there and then add a require "custom_js" to application.js.

  2. Copy all my js files under app/javascript/channels (which should be included by default, since application.js has require("channels")).

  3. Adding require_tree . to application.js, which was the previous approach.

How can I load my own js files inside a Rails 6 application?


回答1:


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") 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.




回答2:


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




回答3:


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

  1. create your custom js file in app/javascripts/packs. Ex: app/javascripts/packs/custom.js.
  2. In your application.js (default it present inside the packs folder), import the custom js file. EX: import './custom.js'
  3. Use this tag <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> in your application.html.erb.
  4. rake assets:precompile

Now refresh the page, Surely it works.

For further doubts please refer my blog. It will helpful Rails 6 - Webpacker



来源:https://stackoverflow.com/questions/56242664/how-to-require-custom-js-files-in-rails-6

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