Angular8的使用(八):打包到tomcat中部署

1.修改build指令

在package.json文件中,修改scripts的build的value值:

{
    
    
  "name": "test-web",
  "version": "0.0.0",
  "scripts": {
    
    
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --base-href /test-web/ --output-path /home/fracong/test/test-web --delete-output-path=false",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  }

说明:
1.修改以下代码"build": "ng build --base-href /test-web/ --output-path /home/fracong/test/test-web --delete-output-path=false"即可。

2.--base-href /test-web/ 是将文件打包后,访问的路径的项目名称为:test-web;
在生成的index.html中,会生成如下代码(href的值):

<base href="/test-web/">  <meta name="viewport" content="width=device-width, initial-scale=1">

3.--output-path 当在编译之后,会自动将生成的项目打包到指定的路径下(通常会部署到tomcat的webapps目录下)实现自动编译部署

2.编译命令和访问

在黑窗口进行编译命令:

npm run build

这个时候在--output-path的路径中,会出现项目文件,这个时候正常启动tomcat即可。并输入以下路径进行访问:

http://localhost:8080/test-web/

3.问题解决

3.1.路由页面刷新出现404

3.1.1.使用hash模式

*弊端:会在路径中出现#号,如http://localhost:8080/test-web/会变成http://localhost:8080/test-web/#/
1.方案一
在app-routing.module.ts中,修改为以下代码:

@NgModule({
    
    
  imports: [
    RouterModule.forRoot(routes, {
    
    useHash: true})
  ],
  exports: [RouterModule]
})

添加{useHash: true} 即可。
2.方案二
在app.module.ts中修改添加以下代码:

import {
    
    HashLocationStrategy, LocationStrategy} from '@angular/common';

@NgModule({
    
    
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
  	{
    
    provide: LocationStrategy, useClass: HashLocationStrategy}
  ],
  bootstrap: [AppComponent]
})

添加{provide: LocationStrategy, useClass: HashLocationStrategy}即可。

3.1.2.修改tomcat

在conf/web.xml中添加:

<error-page>
    <error-code>404</error-code>
    <location>/</location>
</error-page>

*弊端:如果出现真的404页面,无法进行区分。

3.1.4.不使用子路由

所有的模块都继承在副模块上,不存在子路由的时候,这个时候就不会出现404这种情况了!

猜你喜欢

转载自blog.csdn.net/m0_37356874/article/details/102716445