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

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Tobias Kraze
Last edit:
10 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