gloriaJun / til

Lessoned Learned
3 stars 0 forks source link

Define environment variables from env files #24

Open gloriaJun opened 5 years ago

gloriaJun commented 5 years ago

Version

"webpack": "^4.29.6", "dotenv": "^8.0.0",

Define env file

The file name is <rootDir>/.env.

API_URL=https://conduit.productionready.io/api

It can define separate file each stage. (e.g .env.development, .env.production)

Install the dotenv

Install the dotenv library

# with npm 
npm install dotenv

# or with Yarn 
yarn add dotenv

webpack configuration

'use strict';

const path = require('path');
const webpack = require('webpack');
// SKIP...

const isDev = process.env.NODE_ENV !== 'production';
const config = require('dotenv').config(resolve('..', '.env'));

// SKIP...
    new webpack.EnvironmentPlugin({
      ...config.parsed,
    }),
  ],
// SKIP...

Frontend Source

It can be used like the following example.

import axios from 'axios';

const BASE_URL = process.env.API_URL;

const axiosInstance = axios.create({
  baseURL: BASE_URL,
  headers: {},
});
// SKIP...

Reference