Javascript 如何在 Angular 2 CLI 中使用“ng build --prod”和“ng serve --prod”,得到 404 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38610903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use "ng build --prod" and "ng serve --prod" with Angular 2 CLI, getting 404 errors
提问by ganjan
When I try to run ng buildwith the --prod option it compiles into one main.js file and I get no errors in the console.
当我尝试使用 --prod 选项运行ng build 时,它会编译成一个 main.js 文件,并且在控制台中没有出现任何错误。
But when I run the application in the browser it still looks for individual js files.
但是当我在浏览器中运行该应用程序时,它仍然会查找单个 js 文件。
my main.ts:
我的 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?
当然,所有这些请求都会得到 404,因为 js 文件都被压缩到一个 main.js 文件中。我如何避免这种情况?
回答by tony
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/