简体   繁体   English

角环境文件未通过ng serve / build复制

[英]Angular environment file not copied by ng serve/build

I am stuck with this apparently simple issue. 我被这个看似简单的问题所困扰。 I have different env files in angular-cli.json as shown: 我在angular-cli.json有不同的env文件,如下所示:

  "environmentSource": "environments/environment.ts",
  "environments": {
    "local": "environments/environment.local.ts",
    "dev": "environments/environment.dev.ts",
    "test": "environments/environment.test.ts",
    "uat": "environments/environment.uat.ts",
    "staging": "environments/environment.staging.ts",
    "prod": "environments/environment.prod.ts"
  }

I expect that ng serve --environment=local will copy the contents of environment.local.ts to environment.ts , however it is apparently not working. 我希望ng serve --environment=local将把environment.local.ts的内容复制到environment.ts ,但是显然不起作用。 The app does not work if I have an intentional typo in environment.ts . 如果我在environment.ts有故意的错字,则该应用程序无法正常工作。 For example, if I have in environment.local.ts export const baseWebApiUrl = 'http://localhost:63037/api/' and in environment.ts export const baseWebApiUrl = 'http://xxx/api/' - the app fails. 例如,如果我在environment.local.ts中export const baseWebApiUrl = 'http://localhost:63037/api/'而在environment.ts export const baseWebApiUrl = 'http://xxx/api/' -应用失败。 It only works if I also have export const baseWebApiUrl = 'http://localhost:63037/api/' in environment.ts which defeats the purpose of all these different settings files. 它只是如果我也有工作export const baseWebApiUrl = 'http://localhost:63037/api/'environment.ts这违背了所有这些不同的设置文件的目的。

What am I doing wrong? 我究竟做错了什么?

Thanks Anand 谢谢阿南德

In the component where you want to use that environment variable add below import statement: 在要使用该环境变量的组件中,在import语句下面添加:

import { environment } from '../environments/environment';

Then you do a build for your environment: 然后,针对您的环境进行构建:

ng build -env=local

If you try ng serve after this, the application will take the values from corresponding environment file. 如果您尝试此操作,则应用程序将从相应的环境文件中获取值。 Please try this and share results. 请尝试这个并分享结果。

我以为ng serve将采用ng build --env = NAME的输出,但似乎需要同时使用ng build和ng serve --env = NAME

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

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