Skip to content

Instantly share code, notes, and snippets.

@a-m-dev
Last active July 17, 2018 07:25
Show Gist options
  • Save a-m-dev/3a7530cd6c17b6f9a4f6b701201435dc to your computer and use it in GitHub Desktop.
Save a-m-dev/3a7530cd6c17b6f9a4f6b701201435dc to your computer and use it in GitHub Desktop.
/* .env file is the best place to store all your diffrent api endpoint
* this gist is explain hot tyo create one
* best of luck
*/
// #01 -----------------------------------------------------
// create .env file in your root directory and
// add your end points with different names to it like below
// in our case we have one endpoint ( this is base url )
API_URL = http://api.mydomain.com
// #02 ------------------------------------
// npm i -D dotenv
// this pkg going to do every thing for you
// #03 -------------------------------------------------------------------
// use line below to require all env variables to your webpack config file
// this code will find .env file in your project and
// imports all its variables into your webpack file
// by this we gonna be able to access variables from .env file
// with process.env.myVariableFromENVfile
// but before that you need to handle step #04 & #05
require('dotenv').config()
// #04 --------------------------------------------------------------------
// require webpack into your webpack.config file
// we gonna be use its definePlugin method to make webpack to
// replace variables in our project with values of variables from .env file
const webpack = require('webpack')
// #05 -----------------------------------------------------------------------------------
// in the plugin section of your webpack.config.js file
// use webpack.DefinePlugin to define new plugin for each one of your env variables
// by this webpack will file env file variable names in our entire project and replace it
// with the value of the same varibale from .env file
// just make sure to pass string to left side API_URL -< that is b/c we use JSON.stringify
new webpack.definePlugin({
API_URL: JSON.stringify(process.env.API_URL)
})
// #06 -----------------------------------------------------
// reboot your webpack-dev-server
// just stop it from terminal and run it again
// to make webpack to aquire new configurations that we made
// #07 --------------------------------------------------------------------
// use it in when ever place of your project that you want
// for example we are going to use it to fetch some api from some end point
// in our project , webpack will replace the value
import React from 'react'
fetch( API_URL + '/v1/recipes') // just for test , this should be in componentDidMount
.then(res => res.json())
.then(_data => console.log(_data))
const App = () => {
return(
...
)
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment