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:
-
Install
rails-erb-loader
:yarn add rails-erb-loader
-
Add this to your
config/webpacker/environment.js
:environment.loaders.prepend('erb', { test: /\.erb$/, enforce: 'pre', use: [{ loader: 'rails-erb-loader', }] })
-
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.
Posted by Tobias Kraze to makandra dev (2018-10-09 08:35)