平台设置后无法启用prod模式。 Angular 5 Production build

时间:2017-12-08 12:08:59

标签: angular typescript webpack angular-cli angular5

错误:

Uncaught Error: Cannot enable prod mode after platform setup. at main.bundle.js:1 

案例:

使用 ng build --prod 生成构建后,应用启动时出错。但是,使用 ng serve ng build 编译的开发版本都可以正常运行。

我尝试了什么:

- 在this回答后,将全局和本地@angular/cli升级到最新版本,即1.6.0

的package.json:

{
  "dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "auth0-js": "^8.11.3",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "jquery": "^3.2.1",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "^1.6.0",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.2.16",
    "@types/node": "~6.0.60",
    "@types/rx": "^4.1.1",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "^2.6.2"
  }
}

main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.log(err));

重现错误的最小代码:

git/cli-reproapp

1 个答案:

答案 0 :(得分:3)

在您JamesNK提供的示例应用中,由于以下行而发生错误: -

  

export const isInDevMode = isDevMode();

文件cli-reproapp/src/app/app.constants.ts中的

。因此,作为一种解决方法,您可以创建一个函数而不是常量isInDevMode,如下所示。因此,当代码中实际使用isDevMode()时,enableProdMode()稍后会被调用(最重要的是在调用export function isInDevMode():boolean { return isDevMode(); } 之后)。

this.title = isInDevMode ? 'App in dev mode works.' : 'App is prod mode works.'

显然,在此之后,您还需要更改“isInDevMode”常量用于调用新创建的“isInDevMode()”方法的行。因此,在示例应用程序中,您需要替换app.component.ts中的以下行

this.title = isInDevMode() ? 'App in dev mode works.' : 'App is prod mode works.'

这一个: -

{{1}}

您还可以在链接git/cli-reproapp上看到示例应用的工作版本。