Skip to main content

Access Rails constants from Webpack-managed JS

Rails • Asked by Alex Musayev

I'm just starting to use Webpack with Rails, and have a question. Let say there is a constant defined in Rails application. What could be a proper way to access this constant from JavaScript? Assuming this is Webpacker managed bundle.

I came up with the following solution so far, but still looking if there may be some better alternatives.

  1. yarn add rails-erb-loader
  2. Make sure .erb presents in "extensions" list in config/webpack/paths.yml
  3. Create new JS module and import the constant using ERB syntax:

    class Const {
      static get STEPS() {
        return <%= Const::Experiences::WIZARD_PAGES.to_json %>;
      }
    }
    
    export default Const;
    
  4. Use the constant like so:

    import Const from './const.js.erb';
    
    console.log(Const.STEPS);
    

ERB loader is pretty slow. So I'd love to know if there are some better approaches from performance and JS code structure perspectives.


I haven't used the erb loader yet, but you might also consider just storing the json for the wizard pages in the DOM somewhere (probably in a head tag) that Webpack stuff loads. That's what I was showing in the VueJS examples of loading the data attribute for editing records, but since your JSON is more constant it would make more sense to put in the head instead of inside the body.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.