I want to use environment variables with my Rails 6 webpacker project in my js code follow this document https://webpacker-docs.netlify.app/docs/env
First, I create .env file at the root directory of my project.
Then
config/webpack/environment.js (I can access process.env just as expected from here)
const dotenv = require('dotenv')
const dotenvFiles = [
`.env.${process.env.NODE_ENV}.local`,
'.env.local',
`.env.${process.env.NODE_ENV}`,
'.env'
]
dotenvFiles.forEach((dotenvFile) => {
dotenv.config({ path: dotenvFile, silent: true })
})
environment.plugins.insert(
"Environment",
new webpack.EnvironmentPlugin(process.env)
)
console.log(process.env)
/*
{
.
.
.
RAILS_ENV: 'development',
MY_SECRET: 'This_is_my_secret',
RACK_ENV: 'development',
NODE_ENV: 'development'
}
*/
.
.
.
module.exports = environment
But when I run console.log(process.env) from app/javascript/packs/application.js I get empty object {} instead
I have tried these but have no luck.
- Import and run
dotenvagain inconfig/webpack/development.js
// config/webpack/development.js
const dotenv = require('dotenv')
dotenv.config()
- Change to use dotenv-webpack but the result is not difference.
EDIT
After searching for hours I found a workaround from this Adding plugin to Webpack with Rails
For some reason if you run your rails server(rails s) with bin/webpack-dev-server your variables will be inaccessible.