This tutorial is out of date and no longer maintained.
Configuring environment variables (env vars for short) in Angular is now much easier to do. In this tutorial, we shall set environment variables for an AngularJS app using gulp-ng-config
.
This tutorial is relatively easy to follow if you have had experience with environment variables, Gulp, or AngularJS.
Using env vars enables you to separate your source code from your application configuration (or config, for short). This is good practice because config varies substantially across your app deploys, but your code generally does not.
Some benefits you reap by employing env vars are:
env
may be testing
, while on your hosting provider, it changes to production
.Contents of your config and env vars may include things like:
Now that we have got the basics down on environment variables, we can now write our first .env
file.
To start on this project you will have to have the folowing installed:
We need to lay the groundwork for our app first. The contents of our project will include:
├── ./.bowerrc
├── ./.env
├── ./.gitignore
├── ./app
│ ├── ./app/app.less
│ ├── ./app/head.jade
│ ├── ./app/index.jade
│ └── ./app/scripts
│ ├── ./app/scripts/application.js
│ ├── ./app/scripts/config.js
│ ├── ./app/scripts/controllers.js
│ └── ./app/scripts/services.js
├── ./bower.json
├── ./config.js
├── ./gulpfile.js
├── ./index.js
└── ./package.json
We shall start by creating the:
package.json
: Run $ npm init
and follow all the required steps to completion. The name of our app is ngEnvVars
.bower.json
: Run $ bower init
and follow all the steps to completion using the same app name as above..bowerrc
: This will specify to bower where to store all the bower components it installs. Its contents include:.env
FileA .env
file is made up of environment variables, one on each line, that take this format:
ENV_VAR_NAME=env_var_value
Create a new folder named angular-env-vars
on your terminal, change the directory to it and create your .env
file. The contents of your .env
file should look something like this:
API_URL=https://example.com
API_TOKEN=myawesomeapitoken
APP_DEBUG=false
APP_ENV=development
The contents of a .env
file are quite sensitive and should hence be kept private. Be sure to leave it out of your version control system.
You do this by adding it in your .gitignore
. This is a small sample of the contents of a .gitignore
, but a more detailed file can be found here.
# Config Files
.env
# Runtime data
node_modules/
public/
To create our sample app, we shall use jade
and less
, which make writing HTML
and CSS
much easier. Our app shall require a few packages to run:
browser-sync
: to create the server that will host our appbrowserify
: to bundle our different angular modules togetherdotenv
: to load our environment variablesgulp
: the task runner that automates some of our jobsgulp-bower
: installs our bower componentsgulp-jade
: converts our jade files to HTMLgulp-less
: converts our less files to CSSgulp-ng-config
: creates our angular environment constantsvinyl-source-stream
: to aid browserifyLet’s now install them.
In addition to the above, we will need to install angular
and angular material
as our UI framework and font-awesome
for our icons, using bower.
We can now get to writing the code.
Some of your environment variables are shared between your various environments, but there are others that are unique to a particular environment. For instance, on your production environment, may require a BUILDPACK_URL
to be able to build our app. Locally, however, we don’t need it.
We can group relevant env vars of a particular environment together. To do this, we will create a file that returns an object with each environment’s env vars.
Create a file called config.js
on the base directory. We shall use this file to generate the config.json
file that gulp-ng-config
takes in as input.
Gulp will allow us to automate tasks like starting our server and bundling our angular files together. Our main use for gulp here is to load our env vars from the .env
and generate our angular env constants.
First, we’ll create a gulpfile.js
in the base directory. Within it we shall have six main tasks:
jade
: to compile our jade to htmlless
: to compile our less to cssbrowser-sync
: to spun our serverbrowserify
: to bundle our modulesng-config
: to create our angular configbower
: to install our bower dependencieswatch
: to watch for any changes we make and rebuild our appIn addition, we will add two other tasks that build on the above, namely build
and the default
task. For the sake of brevity, I will demo the loading of env vars and the creation of the angular env constants only. However, you can still check out the rest of the full gulp file.
gulp-ng-config
takes two parameters:
ngEnvVars.config
where ngEnvVars
is the name of the angular app, while config
denotes the content of our module. You can, however, name it whatever you may like.createModule
and make it false. It indicates that we will not want a new module created for the env constants, but instead, we will define it on our own later in the code. For a full list of options, you could use, check out the gulp-ng-config
npm page.We will save the resulting config file in app/scripts/
.
We will break up our angular app into four main parts:
gulp-ng-config
.These will all be under the app/scripts
folder. In addition to this, we shall have our index.jade
as our main page, head.jade
to hold all our dependency and styling links, and lastly, app.less
for our styling.
These will be under the app
folder. Check out the jade and less references.
The resulting folder structure will be as follows:
app
├── app.less
├── head.jade
├── index.jade
└── scripts
├── application.js
├── config.js
├── controllers.js
└── services.js
Only two things are involved in creating our main app. First, we define all our dependencies (services, controllers, configs). Then we define our app, with it dependencies, both defined or installed.
We will do this in the app/scripts/application.js
file. We will add the config.js
first, then the services.js
, and finally the controllers.js
. This is because the config is used by the services and the services used by the controllers, and hence should be loaded in that order.
If you have created your .env
, config.js
, and gulpfile.js
, we are now ready to generate our angular config file. Note that, the name of our angular config file will be the same as the name of the config.json
file generated when we run gulp. Remember that this file will be saved in app/scripts/
.
Let’s now get to generating the file.
Running this command will generate the file app/scripts/config.js
, which should look like this:
So now that we have our env vars, we could use them in a service. We shall make a service that logs a message depending on whether APP_DEBUG has been set to true in the .env
. Let’s call this service log
. It shall need 3 things to work:
[$log](https://docs.angularjs.org/api/ng/service/$log)
: An angular service for logging messages to the console.ENV_VARS
: The constant in which our environment variables are stored.[$mdToast](https://material.angularjs.org/latest/demo/toast)
: An angular material toast service that we will use to inform the user when debugging has been set to false.The resultant service takes this form:
Our config file has been used in our service. Now it’s time to use our service in our very simple controller.
I’ve broken down our view into two parts: the head
and the body
. Our head
(app/head.jade
) will contain our links and scripts, while the body
(app/index.jade
) will be host to our page components.
The head:
base(href='/')
meta(charset='utf-8')
meta(name='description' content='angular app that accesses environment variables.')
// Angular material style
link(rel="stylesheet" href="lib/angular-material/angular-material.min.css")
link(rel='stylesheet' href="lib/font-awesome/css/font-awesome.min.css")
link(rel='stylesheet' type='text/css' href='app.css')
// Angular material javascript dependencies
script(src="lib/angular/angular.min.js")
script(src="lib/angular-aria/angular-aria.min.js")
script(src="lib/angular-animate/angular-animate.min.js")
script(src="lib/angular-material/angular-material.min.js")
script(src="lib/angular-resource/angular-resource.min.js")
// Our scripts
script(src="js/application.js")
title ngEnvVars
The main file containing both the body and the head(included as a file) :
doctype html
html(lang="en" ng-app="ngEnvVars")
head
include head
body.bg-color.teal(flex ng-controller="HomeCtrl")
div(flex layout="row" layout-align="center center" style="height: 100%")
div(flex layout="column" layout-align="center center")
span.fa-stack.fa-5x.md-margin
i.fa.fa-circle.fa-stack-2x.text.yellow
i.fa.fa-cogs.fa-stack-1x
p.md-display-1 Angular Env Vars
p with
p.md-title gulp-ng-config
// We display alist of our env constants here
md-list(flex)
md-divider.md-margin
md-list-item.md-2-line(ng-repeat="(key, value) in envVars" ng-click="null")
span.fa-stack.fa-lg.md-margin
i.fa.fa-circle.fa-stack-2x.text.orange
i.fa.fa-wrench.fa-stack-1x
.md-list-item-text.layout-margin
h3(layout="row")
b Env Var:
p {{key}}
p {{value}}
// We use our log service here
md-select(ng-model="logType" aria-label="Log Types")
md-option(ng-repeat="type in ['log', 'info', 'warn', 'error', 'debug']") {{type}}
md-button.bg-color.yellow(ng-click="log()") Log Some Error
All that’s left to do is style our page in the app/app.less
file.
@teal: color("#4ABDAC");
@orange: color("#FC4A1A");
@yellow: color("#F7B733");
@grey: color("#DFDCE3");
* {
margin: 0;
}
html,
body {
height: 100%;
}
.text {
&.orange {
color: @orange !important;
}
&.teal {
color: @teal;
}
&.yellow {
color: @yellow;
}
&.grey {
color: @grey;
}
}
.bg-color {
color: white;
&.teal {
background-color: @teal;
}
&.orange {
background-color: @orange;
}
&.yellow {
background-color: @yellow;
}
&.grey {
background-color: @grey;
}
&.transparent {
background-color: transparent;
}
}
We are now set to launch our app. We do this by running:
Running this command will automatically open the page in your default browser. This should lead to our awesome ngEnvVars
page that should look like:
We now have access to the environment variables in the .env
in our angular app. We have listed them on our page.
In your .env
, set the APP_DEBUG
to true
at first. Run gulp and log a few messages to the console. To view the results on the console on Chrome, type CTRL+SHIFT+I
or COMMAND+OPTION+I
on a mac. You should see something like:
You can later set the APP_DEBUG
to false
. You could open another terminal tab and run:
This command will regenerate the app/scripts/config.js
. Our watch
task in gulp will then rerun the app. When we now try to log to the console using our button, we shall get this message as a toast:
This concludes our tutorial on angular environment variables.
Environment variables are important resources that yield a lot of benefits when kept separate from the code. It is at times difficult to have access to them for use in an angular app, but with gulp-ng-config
, obtaining them is a fairly easy process.
Hopefully, by the end of this tutorial, you will have a good grasp on how to do this.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!