Accessing Rails config in webpack(er)

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 Over 5 years ago