Adding external js files on Rails 6

2020-07-24 15:46发布

问题:

I created a folder named "custom" under app->javascript->packs and place the following external js:

  • metisMenu.min.js
  • startmin.js

Then on under app->javascript->packs->application.js I required the stated js plugin above:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("custom/metisMenu.min").start()
require("custom/startmin").start()
require("channels")


import 'bootstrap'
import './stylesheets/application.scss'

Unfortunately, still this did not work. Any idea what am I doing wrong?

Also is it ok to place all of the custom css under app->javascript->packs->stylesheets (folder) and not on the assets->stylesheets anymore since Rails 6 is using webpacker?

回答1:

Your folder needs to be structured like that:

app/javascript/packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

require("custom")

app/javascript/custom/index.js

require("myScript")
require("mySecondScript")

The myScript.js and mySecondScript.js files, for instance, will be located in the same folder ie app/javascript/custom.



回答2:

You can add custom js files like this:

  1. Add your js files to app/javascript folder

    app/javascript/custom/metisMenu.min.js
    app/javascript/custom/startmin.js
    
  2. Require js files in app/javascript/packs/application.js

    require("@rails/ujs").start()
    require("turbolinks").start()
    require("@rails/activestorage").start()
    
    # custom js files
    require("custom/metisMenu.min")
    require("custom/startmin")
    
  3. Add <%= javascript_pack_tag 'application' %> to application.html.erb

UPDATE

You can add style files like this:

  1. Add your style files to app/javascript folder

    app/javascript/stylesheets/metisMenu.min.scss
    
  2. Import style files in app/javascript/packs/application.js

    import "stylesheets/metisMenu.min"
    
  3. Add <%= stylesheet_pack_tag 'application' %> to application.html.erb
  4. Set extract_css: true in config/webpacker.yml