Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "ng build --prod" and "ng serve --prod" with Angular 2 CLI, getting 404 errors

When I try to run ng build with the --prod option it compiles into one main.js file and I get no errors in the console.

But when I run the application in the browser it still looks for individual js files.

my 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));

When the application runs in the browser it looks for

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

All of these requests get 404 of course since the js files are all compressed to one main.js file. How do I avoid this?

like image 203
ganjan Avatar asked Jul 27 '16 10:07

ganjan


1 Answers

When you build a product, the path changes to the root of the system you are viewing it on, not the root of your app.

Build it by passing the correct path from the system's user root folder to where your built project is located.

Example:

ng build --prod --base-href /tony/myproject/
like image 135
tony Avatar answered Sep 21 '22 13:09

tony