gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:25:50 25 4
gpt4 key购买 nike

有没有办法在构建时评估某些东西,然后在 angular-cli 构建过程中将它添加到应用程序?

用例:

我之前使用 gulp 构建应用程序。你可以执行类似的东西:

 git rev-parse --short HEAD

然后,您可以使用 gulp-replace 将其添加到应用程序中:

const GIT_VERSION = "{GIT_VERSION}";

最后,编译后的应用程序如下所示:

const GIT_VERSION = "59e5722";

angular-cli 是否提供了一些东西来实现这个而不必恢复到 gulp?

最佳答案

如果我没有正确理解您的问题,您是否查看过 Angular2 CLI 的 environment文件?

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). 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:

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

静态解决方案

使用您在每个文件中所需的值修改这些文件将在构建时将它们合并到每个相应的构建中。

例如,environment.dev.ts 可能如下所示:

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

动态解决方案

如果您正在寻找更强大/更动态的东西,您可以使用像 replace-in-file 这样的插件,连同环境文件,最好在 How to insert a Build Number or Timestamp at build time in AngularCLI 的接受答案中描述和 Volodymyr Bilyachat的博文 Angular 2 - Manage application version这将允许以下内容:

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

关于angular - 如何使用 angular-cli 将构建时环境变量添加到应用程序中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41895643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com