Accessing Rails config in webpack(er)

Posted . Visible to the public.

It is possible to access Rails config (for example secrets) from within your webpack bundles, thanks to rails-erb-loader Show archive.org snapshot . When using webpacker, the setup is like this:

  1. Install rails-erb-loader:

    yarn add rails-erb-loader
    
  2. Add this to your config/webpacker/environment.js:

    environment.loaders.prepend('erb', {
      test: /\.erb$/,
      enforce: 'pre',
      use: [{
        loader: 'rails-erb-loader',
      }]
    })
    
  3. Start using erb. For example, in a file api_config.js.erb:

    /* rails-erb-loader-dependencies ../config/secrets.yml */
    
    export default {
      apiKey: '<%= Rails.application.secrets[:api][:key] %>'
    }
    

This works by simply calling bin/rails runner with the correct environment. The rails-erb-loader-dependencies comment is only needed to make the webpack-dev-server automatically regenerate the file, when your secrets.yml changes.

Tobias Kraze
Last edit
Tobias Kraze
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2018-10-09 08:35)