Angular7在生产模式下:未捕获ReferenceError:环境未定义

时间:2019-02-23 11:01:22

标签: javascript angular typescript npm angular-cli

我的应用程序在开发中运行良好,并且ng build --prod --source-map成功地构建了应用程序。但是,当我尝试在浏览器中访问它时,出现此错误:

app.module.ts:47 Uncaught ReferenceError: env is not defined
    at Object.zUnb (app.module.ts:47)
    at u (bootstrap:81)

这是我的app.module.ts文件(相关部分):

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { APP_BASE_HREF } from '@angular/common';
import { HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { environment as env } from '@env/environment'; // <- import env
import { CoreModule } from '@app/core/core.module';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MatSidenavModule,
    CoreModule,
    AppRoutingModule,
  ],
  providers: [
    { provide: APP_BASE_HREF, useValue: env.baseHref } // <--- error
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

这是我的tsconfig.json文件,其中定义了@env路径:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./src/",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "paths": {
      "@app/*": ["app/*"],
      "@env/*": ["environments/*"]
    }
  }
}

2 个答案:

答案 0 :(得分:0)

import { environment } as env from '@env/environment';

这应该可以解决问题...

答案 1 :(得分:0)

我将@angular-devkit/build-angular从版本~0.6.0升级到^0.13.3,就解决了这个问题。