Reputation: 1875
Is it possible to access my Rails environment variables from webpacker bundles? I know I can use dotenv, but the project uses Figaro and I would prefer not to change that. I would really like to pass the env vars from Rails to webpacker during compilation of the bundles.
Upvotes: 2
Views: 3002
Reputation: 1663
I'm using webpacker 5.4.3
and I use dotenv-webpack to solve this problem.
yarn add -D dotenv-webpack
Put the ".env*" files in your Rails project root directory, then edit environment.js:
// config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const Dotenv = require('dotenv-webpack');
environment.plugins.prepend('Dotenv', new Dotenv());
// your other settings...
module.exports = environment
Then you can access the environments through process.env
# .env
ABC=123
//packs/application.js
console.log(process.env.ABC)
// => 123
Upvotes: 1
Reputation: 171
I just ran into the same problem. If you put your .env
file in config/webpack
and then add this code to your config/webpack/application.js
file, you should be good:
const dotenv = require('dotenv')
dotenv.config({path: __dirname + '/.env'})
environment.plugins.insert(
"Environment",
new webpack.EnvironmentPlugin(process.env)
)
Upvotes: 1