Posted 12 months ago. Visible to the public.

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. 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.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Tobias Kraze
Last edit:
11 months ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more