对于最终构建为的Angular 7应用程序

- main.js
- assets
  -- assets/img

带有一个引用 Assets 的component/html
src='./assets/img/img1.jpeg'

该应用程序将分配给不同的团队,并可以在不同的根目录上托管
example.com/route/first
example2.com/route/second

如果消费者将我的构建内容称为<script src=''../some-dir/libs/main.js">
Angular应用程序将查看当前路径以查找 Assets (example.com/route/first/assets),这将迫使它们复制粘贴我提供给其根目录的 Assets 文件夹。我想,如果我的组件可以在相对于我的构建内容('../some-dir/libs/asset')的位置而不是其目录根目录下查找我的 Assets ,那么对于客户而言,这将更加简单。但是我不太确定我期望的是行业标准还是适当的标准

如何仅通过提取和引用/导入我的构建内容来正确构建/捆绑/引用消费者可以在任何地方使用的 Assets ?
(我不需要知道使用者的项目结构,使用者也不需要更改我/他的文件夹结构)

最佳答案

只需在应用程序中使用相对网址,如下所示:

<img src='./assets/img/img1.jpeg' />

如果您知道根上下文在哪里,请使用base-hrefdeploy-url参数构建您的应用程序,如下所示:
ng build --prod --base-href=/route1/ --deploy-url=/route1/

如果需要部署到其他根上下文中,请更改参数的值并重新构建。

但是,如果您不知道部署根上下文,则计划B为:

useHash更改为true中的app-routing.module.ts
const routes: Routes = [/* your routes goes here */];

@NgModule({
    imports: [
        RouterModule.forRoot(routes, {
            useHash: true, // change useHash to true
            enableTracing: !environment.production
        })
    ],
    exports: [RouterModule]
})
export class AppRoutingModule { }

并将base href中的index.html更改为./
<head>
  <base href="./">
</head>

不要在上添加base-hrefdeploy-url参数,然后将应用程序部署到任何Web根目录。但网址将以ng build结尾

关于angular - 如何为在其他地方加载的 Angular 应用程序捆绑 Assets ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55255390/

10-11 22:50
查看更多