6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel Mixで環境に応じて複数の.envで環境変数を管理する

Posted at

はじめに

こんにちは。先日、ランニングシューズ以外でいい靴を買ってしまいました、筆者です:smile:

さて、LaravelでWebpack使っているので、Laravel Mixを使用しております。

その際に**.env**で環境変数を分ける機会がありましたので、共有します。

結論

急いでいる方はこちらご参照くださいませ。Laravel Mixのドキュメントの書いてあるんです:ok_hand:
(ただ、スター:star:が超少ないのが気になります...:thinking:)

解説

1. mix-env-file をインストールする。

$ npm install mix-env-file

2. dotenv をインストールする。

あとでコンパイルするときにインストールしろと怒られるのでこちらもインストールします。
(ドキュメントには書いてないんです:sob:)

$ npm install dotenv

3. package.jsonを編集する。

サンプルはこちら↓

package.json
"scripts": {
  "dev": "cross-env ENV_FILE=./.env.dev npm run development",
  "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
  "watch": "npm run development -- --watch",
  "watch-poll": "npm run watch -- --watch-poll",
  "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
  "prod": "cross-env ENV_FILE=./.env.prod npm run production",
  "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
}

上記の場合、以下の動きをします。
npm run devしたときは、./.env.devを読みます。
npm run prodしたときは、./.env.prodを読みます。

4. webpack.mix.js を編集する。

webpack.mix.js
let mix = require('laravel-mix');
require('mix-env-file');

// Then pass your file to this plugin
// If this is not set, this plugin won't do anything and the default .env variables will remain
mix.env(process.env.ENV_FILE);

以上です:ok_hand:

おわりに

.env便利でした:smile:
それでは!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?