Access Rails constants from Webpack-managed JS
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.
yarn add rails-erb-loader
- Make sure
.erb
presents in "extensions" list inconfig/webpack/paths.yml
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;
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.