Read more

Accessing Rails config in webpack(er)

Tobias Kraze
October 09, 2018Software engineer at makandra GmbH

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] %>'
    }
    
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Tobias Kraze to makandra dev (2018-10-09 10:35)