LoginSignup
6
7

More than 3 years have passed since last update.

javascriptでenvファイルを使う

Last updated at Posted at 2020-02-26

javascriptでenvファイルを使う実装をまとめます。

前提条件

  • npmがインストールされていること

インストール

npmコマンドでモジュールをインストール

$ npm i --save dotenv

使い方

ファイルの作成

touchコマンドでtest.jsファイル、.envファイルを作成

$ touch test.js .env
test.js
require('dotenv').config()
const { BASE_URL } = process.env

console.log(BASE_URL)
.env
BASE_URL="http://localhost:8000/"

実行

nodeコマンドでtest.jsを実行する

$ node test

出力結果

http://localhost:8000/

Nuxt.jsで使う場合

npmコマンドでモジュールをインストール

$ npm i --save @nuxtjs/dotenv
nuxt.config.js
module.exports = {
  modules: [
    '@nuxtjs/dotenv', // 追記
  ]
}

参考文献

この記事は以下の情報を参考にして執筆しました。

6
7
0

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
6
7