相关文章推荐
腼腆的凳子  ·  mysql ...·  1 年前    · 
任性的香瓜  ·  数据库 CI/CD 工具 -- ...·  2 年前    · 
3
1

More than 1 year has passed since last update.

Nuxt で環境変数を使用するときに気をつけること

Posted at

※ Nuxt v2.15.8 を使用しております。

Runtime config プロパティはキャストされる

Nuxt で環境変数を扱うには、 env プロパティ Runtime config プロパティ があります。 env プロパティから Runtime config プロパティへ移行したところ環境変数がキャストされ、同値演算子( === )で比較している式が失敗するという不具合に遭遇しました。(以下のような issue も立てられています。)

mounted () { console . log ( ' --- env プロパティ --- ' ) console . log ( ` ${ process . env . text } : ${ typeof process . env . text } ` ) console . log ( ` ${ process . env . num } : ${ typeof process . env . num } ` ) console . log ( ` ${ process . env . flag } : ${ typeof process . env . flag } ` ) console . log ( ' --- Runtime config プロパティ --- ' ) console . log ( ` ${ this . $config . text } : ${ typeof this . $config . text } ` ) console . log ( ` ${ this . $config . num } : ${ typeof this . $config . num } ` ) console . log ( ` ${ this . $config . flag } : ${ typeof this . $config . flag } ` )

コンソールログを確認します。

--- env プロパティ ---
text: string
123: string
true: string
--- Runtime config プロパティ ---
text: string
123: number
true: boolean

以下のように .env ファイルで値をダブルクォートで囲んだり、 nuxt.config.js ファイルで文字列として設定してもキャストされます。

TEXT=text
# ダブルクォートで囲んでもキャストされる
NUM="123"
FLAG="true"
nuxt.config.js
export default {
  publicRuntimeConfig: {
    text: process.env.TEXT,
    // テンプレートリテラルを使用しても number 型にキャストされる
    num: `${process.env.NUM}`,
    // 空文字列を足しても boolean 型にキャストされる
    flag: process.env.FLAG + '',
対策1: 環境変数で扱う値を string 型にする

上記の再現の場合、 FLAG=true は改善できます。例えば FLAG によってノーマルモードとハードモードに分けている場合は以下のように命名を MODE などに変更し、 boolean 型以外の値を設定します。

- FLAG=true
+ MODE=hard
対策2: コード上で環境変数を string 型にキャストする

環境変数を使用するときにテンプレートリテラルなどを使用して、 string 型にキャストします。

if (`${this.$config.num}` === "123") {...}

nuxt.config.js ファイルで文字列として設定してもキャストされるのは厄介です。ですので、環境変数で扱う値を初めから string 型になるように定義することでキャストされることを未然に防ぎましょう。

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
What you can do with signing up
1