Help us understand the problem. What is going on with this article?

フロントエンドでdotenvを使えるようにしてみた

More than 1 year has passed since last update.

目的

フロントエンドでprocess.env.NODE_ENV==="development"とかで条件分岐したかったので、コンパイル時にprocess.env.NODE_ENVを.envファイルにあるNODE_ENVの値を引っ張ってきて"development"==="development"と"使われてる値だけ"埋め込むようにする。

対象

webpack2が導入できている。

STEP1 dotenvをインストール

dotenvは.envファイルをパースして読み込んでくれます。
optionを指定すれば、.env.productionなどをそのまま読み込めるようにできます。

$ npm install dotenv --save-dev

STEP2 envを展開するモジュールを作成

// .envを展開
dotenv = require('dotenv');
let options = {};
if (process.env.NODE_ENV === 'production') {
    options.path = '.env.production';
}
dotenv.config(options);

function middleware(value) {
    if (value === "true") return true;
    if (value === "false") return false;
    if (value === "0" || value === 0) return 0;
    return value || null;
}

exports.getEnvs = () => {
    let env = {};
    for (let key in process.env) {
        if (process.env[key]) {
            env['process.env.' + key] = JSON.stringify(middleware(process.env[key]));
        }
    }
    return env;
};

STEP3 webpack.DefinePluginを使ってみる

webpack.config.js
const path = require('path'),
    webpack = require('webpack'),
    env = require(path.join(__dirname, '/src/config/env.js'));

module.exports = {
    entry: {
        app: [
            'babel-polyfill',
            path.resolve(__dirname, 'src/index.js')
        ]
    },
    plugins: [
        new webpack.DefinePlugin(env.getEnvs())
    ],
    output: {
        path: path.resolve(__dirname, 'public/assets/js/dist/'),
        filename: 'game.js'
    },
};

これで好きなところでprocess.env.*を使えるよになりました!
気に入ったらいいねとストックとフォローお願いします!

注意:envの値を変更したら毎回コンパイルし直してください。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away