【问题标题】:How to use "ng build --prod" and "ng serve --prod" with Angular 2 CLI, getting 404 errors如何在 Angular 2 CLI 中使用“ng build --prod”和“ng serve --prod”,出现 404 错误
【发布时间】:2016-07-27 10:51:38
【问题描述】:

当我尝试使用 --prod 选项运行 ng build 时,它会编译成一个 main.js 文件,并且在控制台中没有出现任何错误。

但是当我在浏览器中运行应用程序时,它仍然会查找单个 js 文件。

我的 main.ts:

// default
import { provide, enableProdMode, ExceptionHandler } from '@angular/core';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS, Http } from '@angular/http';

// External
import {
  TranslateService, TranslateLoader, TranslateStaticLoader
} from 'ng2-translate/ng2-translate';
import {Angulartics2} from 'angulartics2';

// mine
import { CustomExceptionHandler } from './app/_common/CustomExceptionHandler';
import { UserService } from './app/_services/user.service';
import { MessagesService } from './app/_services/messages.service';
import { APP_ROUTER_PROVIDERS } from './app/app.routes';
import { App, environment } from './app/';

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

bootstrap(App, [
  APP_ROUTER_PROVIDERS,
  HTTP_PROVIDERS,
  provide(ExceptionHandler, { useClass: CustomExceptionHandler }),
  provide(LocationStrategy, { useClass: HashLocationStrategy }),
  {
    provide: TranslateLoader,
    useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
    deps: [Http]
  },
  Angulartics2,
  TranslateService,
  MessagesService,
  UserService
])
.then(() => {
  console.log('Angular 2 loaded');
})
.catch(err => console.error(err));

当应用程序在浏览器中运行时,它会寻找

app/_services/messages.service.js
app/_services/user.service.js
app/app.routes.js
etc...

所有这些请求当然都会得到 404,因为 js 文件都被压缩到一个 main.js 文件中。我该如何避免这种情况?

【问题讨论】:

  • 你能检查一下是否提供了正确的 main.js 吗?
  • @ArpitAgarwal 我相信是的

标签: javascript angular production-environment angular-cli


【解决方案1】:

当您构建产品时,路径会更改为您正在查看它的系统的根目录,而不是您应用的根目录。

通过将正确的路径从系统的用户根文件夹传递到您构建的项目所在的位置来构建它。

例子:

ng build --prod --base-href /tony/myproject/

【讨论】:

  • ng build --prod --base-href /tony/myproject/ 更正“-prod”上的“--” :)
猜你喜欢
  • 2018-02-07
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 1970-01-01
相关资源
最近更新 更多