简体   繁体   English

如何使用angular-cli将构建时环境变量添加到应用程序中?

[英]How do I add build-time environment variables into application with angular-cli?

Is there a way to evaluate something at build time, and then add it to the application during an angular-cli build process? 有没有办法在构建时评估某些内容,然后在angular-cli构建过程中将其添加到应用程序中?

Use case: 使用案例:

I was previously building an application with gulp. 我以前用gulp构建了一个应用程序。 You could execute something like: 您可以执行以下操作:

 git rev-parse --short HEAD

And then, you could use gulp-replace to add it into the application: 然后,您可以使用gulp-replace将其添加到应用程序中:

const GIT_VERSION = "{GIT_VERSION}";

And finally, the compiled application would look like: 最后,编译的应用程序看起来像:

const GIT_VERSION = "59e5722";

Does angular-cli provide something to achieve this without having to revert to gulp? angular-cli是否提供了一些东西来实现这一点,而不必恢复吞咽?

If I'm understanding your question correctly, have you looked into Angular2 CLI's environment files? 如果我正确理解您的问题,您是否考虑过Angular2 CLI的环境文件?

ng build can specify both a build target ( --target=production or --target=development ) and an environment file to be used with that build ( --environment=dev or - -environment=prod ). ng build可以指定构建目标( --target=production--target=development )和要与该构建一起使用的环境文件( --environment=dev或 - -environment=prod )。 By default, the development build target and environment are used. 默认情况下,使用开发构建目标和环境。

The mapping used to determine which environment file is used can be found in angular-cli.json: 用于确定使用哪个环境文件的映射可以在angular-cli.json中找到:

 "environments": { "source": "environments/environment.ts", "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts" } 

Static Solution 静态解决方案

Modifying these files with the values you needed in each will incorporate them into each respective build, at build-time. 使用每个文件中所需的值修改这些文件将在构建时将它们合并到每个相应的构建中。

For example, an environment.dev.ts might look like this: 例如,environment.dev.ts可能如下所示:

export const environment = {
  production: false,
  apiUrl: 'http://dev-api.mysite.com/v1/',
  loggingEnabled: true,
  environmentName: 'Development'
};

Dynamic Solution 动态解决方案

If you're looking for something a little more robust/dynamic you can use a plugin like replace-in-file , in conjunction with the environment files, best described in the accepted answer of How to insert a Build Number or Timestamp at build time in AngularCLI and Volodymyr Bilyachat 's blog post Angular 2 - Manage application version which would allow something along the lines of: 如果你正在寻找一些更强大/动态的东西,你可以使用像文件替换这样的插件,结合环境文件, 在构建时如何插入构建号或时间戳的接受答案中最好的描述。 在AngularCLIVolodymyr Bilyachat的博客文章Angular 2 - 管理应用程序版本 ,它将允许以下内容:

export const environment = {
  production: false,
  version: '{BUILD_VERSION}',
  apiUrl: 'http://dev-api.mysite.com/v1/',
  loggingEnabled: true,
  environmentName: 'Development'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM