angular gulp
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.
现在,在Angular中配置环境变量(简称env vars)更加容易。 在本教程中,我们将使用gulp-ng-config为AngularJS应用设置环境变量。
This tutorial is relatively easy to follow, if you have had experience with environment variables, Gulp or AngularJS.
如果您有使用Gulp或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.
使用env vars可使您将源代码与应用程序配置(或简称config)分开。 这是一个好习惯,因为在您的应用程序部署中,配置会有很大不同,但您的代码通常不会。
Some benefits you reap by employing env vars are:
您可以通过使用env var获得一些好处:
env
may be testing
, while on you hosting provider, it changes to production
. 只需更改环境名称,即可在一个环境与另一个环境之间轻松切换 。 例如,在持续集成的服务,您的env
可testing
,而在你的托管服务提供商,它变成production
。 Contents of your config/env vars may include things like:
您的config / env var的内容可能包括以下内容:
Now that we have got the basics down on environment variables, we can now write our first .env
file.
现在我们已经了解了环境变量的基础知识,现在我们可以编写第一个.env
文件。
To start on this project you will have to have the folowing installed:
要开始这个项目,您将必须安装以下软件:
We need to lay the ground work 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:
我们将从创建以下内容开始:
$ npm init
and follow all the required steps to completion. The name of our app is ngEnvVars
. package.json :运行$ npm init
并完成所有必需的步骤。 我们的应用程序名为ngEnvVars
。 $ bower init
and follow all the steps to completion using the same app name as above. bower.json :运行$ bower init
并按照与上述相同的应用程序名称完成所有步骤。 {
"directory": "./public/lib"
}
A .env
file is made up of environment variables, one on each line, that take this format:
.env
文件由环境变量组成,每行一个,采用以下格式:
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:
在终端上创建一个名为angular-env-vars
的新文件夹,将目录更改.env
文件夹并创建.env
文件。 .env
文件的内容应如下所示:
API_URL=https://myawesomeapi.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.
.env
文件的内容非常敏感,因此应保密。 确保将其保留在版本控制系统之外。
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.
您可以通过将其添加到.gitignore
。 这是.gitignore
内容的一小部分,但可以在此处找到更详细的文件。
# 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:
要创建示例应用程序,我们将使用jade
和less
,这将使编写HTML
和CSS
更加容易。 我们的应用程序需要运行以下软件包:
Let's now install them.
现在安装它们。
$npm install browser-sync browserify dotenv gulp gulp-bower gulp-jade gulp-less gulp-ng-config vinyl-source-stream --save
In addition to the above, we will need to install angular, angular material as our UI framework and *font-awesome *for our icons, using bower.
除上述内容外,我们还需要使用凉亭安装有角度的,有角度的材质作为我们的UI框架,并为我们的图标安装* 真棒字体* 。
$ bowerinstall angular angular-material font-awesome --save
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.
您的某些环境变量在各种环境之间共享,但有些变量对于特定环境是唯一的。 例如,在您的生产环境中,可能需要BUILDPACK_URL
才能构建我们的应用程序。 但是,在本地,我们不需要它。
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.
在基本目录上创建一个名为config.js
的文件。 我们将使用该文件生成gulp-ng-config
接受作为输入的config.json
文件。
// Shared env vars in all environments
var shared = {
apiUrl: process.env.API_URL || "http://localhost:3000/api",
apiToken: process.env.API_TOKEN,
debug: process.env.DEBUG || true
};
//
var environments = {
development: {
ENV_VARS: shared
},
staging: {
ENV_VARS: shared
},
production: {
ENV_VARS: shared
}
};
environments.production.buildpack = process.env.BUILDPACK_URL;
module.exports = environments;
Gulp will allow use to automate tasks like start our server and bundle 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.
Gulp将允许用于自动化任务,例如启动我们的服务器并将我们的Angle文件捆绑在一起。 gulp在这里的主要用途是从.env加载我们的env var并生成我们的角度env常数。
First, we'll create a gulpfile.js
in the base directory. Within it we shall have six main tasks:
首先,我们将在基本目录中创建一个gulpfile.js
。 其中将有六个主要任务:
In 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.
另外,我们将添加基于以上内容的其他两个任务,即build
和default
任务。 为了简洁起见,我将仅演示env var的加载和角度env常量的创建。 但是,您仍然可以检出完整gulp文件的其余部分。
// If the app environment is not set, we default to development
var ENV = process.env.APP_ENV || 'development';
// Here, we use dotenv to load our env vars in the .env, into process.env
if (ENV === 'development') {
require('dotenv').load();
}
// Our dependencies and paths of files we use
var gulp = require('gulp'),
gutil = require('gulp-util'),
source = require('vinyl-source-stream'),
ngConfig = require('gulp-ng-config'),
path = require('path'),
fs = require('fs'),
config = require('./config.js'),
paths = {
public: {
path: 'public/',
script: './public/js/',
lib: './public/lib/'
},
app: {
jade: ['!app/shared/**', 'app/**/*.jade'],
styles: 'app/styles/*.+(less|css)',
staticFiles: [
'!app/**/*.+(less|css|js|jade)',
'!app/images/**/*',
'app/**/*.*'
],
scripts: {
app: './app/scripts/application.js',
all: './app/scripts/**/*.js'
}
}
};
/*
* We first generate the json file that gulp-ng-config uses as input.
* Then we source it into our gulp task.
* The env constants will be a saved as a sub-module of our app, ngEnVars.
* So we shall name it ngEnvVars.config.
*/
gulp.task('ng-config', function() {
fs.writeFileSync('./config.json',
JSON.stringify(config[ENV]));
gulp.src('./config.json')
.pipe(
ngConfig('ngEnvVars.config', {
createModule: false
})
)
.pipe(gulp.dest('./app/scripts/'))
});
/*
* Browserify bundles our Angular env constants,
* services and controllers together into one file.
* So, ng-config has to run first, to generate the angular env contants.
* We shall add ng-config as a dependency of browserify, so that it runs before it.
*/
gulp.task('browserify', ['ng-config'], function() {
return browserify(paths.app.scripts.app).bundle()
.on('success', gutil.log.bind(gutil, 'Browserify Rebundled'))
.on('error', gutil.log.bind(gutil, 'Browserify ' +
'Error: in browserify gulp task'))
.pipe(source('application.js'))
.pipe(gulp.dest('./public/js/'));
});
gulp-ng-config
takes two parameters:
gulp-ng-config
两个参数:
We will save the resulting config file in app/scripts/
.
我们将生成的配置文件保存在app/scripts/
。
We will break up our angular app into four main parts:
我们将把角度应用分为四个主要部分:
gulp-ng-config
. 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.
这些都将在app/scripts
文件夹下。 除此之外,我们将index.jade
作为主页, head.jade
所有依赖项和样式链接,最后, app.less
用于样式设置。
These will be under the app
folder. Jade and Less are pretty straight-forward, but if you would like to find out more about it, check out the jade and less references.
这些将位于app
文件夹下。 玉和少是相当直接的,但如果你想更多的了解它,检查出玉石和较少的引用。
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.
我们将在app/scripts/application.js
文件中执行此操作。 我们将首先添加config.js
,然后添加services.js
,最后添加controllers.js
。 这是因为配置由服务使用,而控制器使用的服务也应按此顺序加载。
(function() {
'use strict';
// Sub-modules of the app
angular.module('ngEnvVars.controllers', []);
angular.module('ngEnvVars.services', []);
angular.module('ngEnvVars.config', []);
// Constants
require('./config.js');
// Services
require('./services.js');
// Controllers
require('./controllers.js');
// Definition of the ngEnvVars app and its dependencies
window.app = angular.module('ngEnvVars', [
'ngEnvVars.config',
'ngEnvVars.controllers',
'ngEnvVars.services',
'ngMaterial'
]);
}());
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/
.
如果您已经创建了.env
, config.js
和gulpfile.js
,我们现在就可以生成我们的角度配置文件了。 请注意,我们的角度配置文件的名称将与运行gulp时生成的config.json
文件的名称相同。 请记住,该文件将保存在app/scripts/
。
Let's now get to generating the file.
现在开始生成文件。
$ gulp ng-config
Running this command will generate the file app/scripts/config.js
, which should look like this:
运行此命令将生成文件app/scripts/config.js
,该文件应如下所示:
angular.module("ngEnvVars.config")
.constant("ENV_VARS", {
"apiUrl": "https://myawesomeapi.com",
"apiToken": "myawesomeapitoken",
"debug": true,
"env": "development"
});
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:
现在我们有了env var,我们可以在服务中使用它们了。 我们将做出注销取决于APP_DEBUG是否已经被设置为true的消息服务.env
。 我们将此服务日志称为。 它需要做三件事:
The resultant service takes this form:
结果服务采用以下形式:
angular.module('ngEnvVars.services')
.factory('log', ['$log', 'ENV_VARS', '$mdToast',
function($log, ENV_VARS, $mdToast) {
/* Calling this service returns a function that takes in
* the type os a message and the message itself
*/
return function(type, msg) {
/* If debug has been set to true, logging will be enabled.
* Otherwise, a toast will be displayed informing the user that
* this feature is disabled for that particular environment
*/
if (ENV_VARS.debug === true) {
if (type) {
$log[type](msg);
$mdToast.showSimple('Just printed a ' + type +
' message to the console');
} else {
$mdToast.showSimple('You have to specify' +
' a message type first');
}
} else {
$mdToast.showSimple('This environment is not ' +
'configured to log anything at this time');
}
};
}
]);
Our config file has used in our service. Now it's time to use our service in our very simple controller.
我们的配置文件已在我们的服务中使用。 现在是时候在非常简单的控制器中使用我们的服务了。
angular.module('ngEnvVars.controllers')
.controller('HomeCtrl', ['$scope', 'log', 'ENV_VARS',
function($scope, log, ENV_VARS) {
// This will contain our envars
$scope.envVars = ENV_VARS;
// This will log a message to the console
$scope.log = function() {
log($scope.logType, 'You have logged a ' +
$scope.logType + ' message to the console');
};
}
]);
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.
我将我们的观点分为两部分: 头部和身体 。 我们的标头 ( app/head.jade
)将包含我们的链接和脚本,而正文 ( app/index.jade
)将作为我们页面组件的宿主。
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.
剩下要做的就是在app/app.less
文件中设置页面样式。
@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:
现在,我们准备启动我们的应用程序。 我们通过运行以下命令来做到这一点:
$ gulp
Running this command will automatically open the page in your default browser. This should lead to our awesome ngEnvVars
page that should look like:
运行此命令将自动在默认浏览器中打开页面。 这应该会导致我们的ngEnvVars
页面很棒,如下所示:
We now have access to the environment variables in the .env
in our angular app. We have listed them on our page.
现在,我们.env
在我们的角度应用程序中访问.env
中的环境变量。 我们已经在页面上列出了它们。
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 Cmd + Opt + I
on a mac. You should see something like:
在你.env
,设置APP_DEBUG
起初为true。 运行gulp并将一些消息记录到控制台。 要在Chrome的控制台上查看结果,请在Mac上键入Ctrl + Shift + I
或Cmd + Opt + I
。 您应该看到类似以下内容:
You can latter set the APP_DEBUG
to false. You could open another terminal tab and run:
APP_DEBUG
,您可以将APP_DEBUG
设置为false 。 您可以打开另一个终端选项卡并运行:
$ gulp ng-config
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:
该命令将重新生成app/scripts/config.js
。 然后,我们在gulp中的watch
任务将重新运行该应用程序。 现在,当我们尝试使用按钮登录控制台时,我们将获得以下消息:
This concludes our tutorial on angular environment variables.
这样就结束了我们关于角度环境变量的教程。
Environment variables are important resources that yeild 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.
环境变量是重要的资源,当与代码分开存放时,它们会带来很多好处。 有时很难访问它们以在角度应用程序中使用,但是使用gulp-ng-config
,获取它们是一个相当简单的过程。
Hopefully, by the end of this tutorial, you will have a good grasp on how to do this.
希望到本教程结束时,您将对如何执行此操作有很好的了解。
翻译自: https://scotch.io/tutorials/properly-set-environment-variables-for-angular-apps-with-gulp-ng-config
angular gulp