Search code examples
ruby-on-railswebpacker

unsure of what application.js in webpacker-rails is requiring


I have a rails 6 application with

gem 'webpacker', '~> 4.0'
gem 'react-rails'

included in the gemfile,

I've run rails webpacker:install:react rails generate react:install and yarn install

And I notice that there is an application.js file present in my javascript/packs folder:

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

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


// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

Why does it need to require those specific items? Why are some of the requires prefixed with @rails ?


Solution

  • Depending on your application, you may be able to remove some or all of those requires.

    • the @rails/ujs package adds unobtrusive JavaScript features like ajaxifying a form with the remote: true option, and adding the CSRF token to Ajax requests.
    • turbolinks “makes it faster to navigate the application. When you follow a link, Turbolinks automatically fetches the page, swaps in its body tag and merges its head tag, all without incurring the cost of a full page load.” If using, use with care and understand the tradeoffs https://github.com/turbolinks/turbolinks/blob/master/README.md
    • the @rails/activestorage package is only necessary if you’re using ActiveStorage on the backend to support file uploads
    • the channels package is only necessary if you’re using the Rails websocket feature ActionCable

    The @rails/ prefix is just part of the given package’s name to indicate that it is owned by an org; this is typically just a way to avoid name conflicts with other packages that might have the same name.