LoginSignup
11
9

More than 3 years have passed since last update.

Rails + webpacker で.envファイルで環境変数を管理する方法

Posted at

概要

Ruby + webpackerでもdotenv Ruby gemのように環境変数を.envで管理して使いたい!
という方向けの記事です。
そのうちwebpackerのデフォルト機能にしてくれるでしょう(願望)。

検証環境

  • Rails 5.2.2
  • webpacker 3.5

やり方

  • dotenv Ruby gemと同じように、.envに環境変数を用意しておく
  • yarn add dotenvを実行
  • config/webpack/environment.jsを下記のように編集
  • console.log(process.env.FOO)で環境変数をJSから使えます!
// config/webpack/environment.js

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
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.prepend('Environment',
  new webpack.EnvironmentPlugin(
    JSON.parse(JSON.stringify(process.env))
  )
)

module.exports = environment

参考

11
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9