Ask A Question

Notifications

You’re not receiving notifications from this thread.

Access Rails constants from Webpack-managed JS

Alex Musayev asked in Rails

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.

Reply

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.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.