【问题标题】:Use relative path for svg in Angular Library Component在 Angular 库组件中使用 svg 的相对路径
【发布时间】:2020-01-15 15:01:12
【问题描述】:

我使用 Angular Cli 创建了一个自定义库。它的结构如下:

 - dist
 - projects 
    - customLib
        - src
            - assets
                - icons
            - lib
                - button

按钮组件作为 Input() 获取将在按钮内显示的 svg 图标的名称:

  import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'lib-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.scss']
 })

export class ButtonComponent implements OnInit {
svgIconUrl: string;

constructor() {
}

ngOnInit() {
  if (this.icon) {
    this.svgIconUrl = '../../assets/icons/' + this.icon + '.svg';
  }
}}

按钮组件的html:

<button>
   <div *ngIf="svgIconUrl">
    <svg-icon [src]="svgIconUrl"></svg-icon>
   </div>
</button>

我制作了一个脚本,它复制所有图标(存储在 src/assets/icons 中)并将其粘贴到 dist 文件夹中。所有这一切都很好。然后,我在 bitbucket 上发布了我的库,并将它安装在另一个 Angular 应用程序中。 库已正确导入,但 angular-svg-icon 无法找到 svg,因为它正在 localhost:4200/#/assets/icons/myicon.svg 中获取 svg

当然它没有找到 svg,因为它在库中,所以它在“node_modules”文件夹中。如何强制库的按钮组件在库中获取 svg,所以使用相对路径?

这是我使用按钮的 Angular 应用程序(正在导入和使用库)中的 html:

    <lib-button icon="icon-magic"></lib-button>

【问题讨论】:

  • 嗨,找到答案了,我想知道吗?有同样的问题;我的意思是,可能会创建库 PostInstall 的附加脚本(从 ng-package.json 分配的“资产”子句再次复制到用户点的某个可服务位置,谁安装你的库);或者我只使用 base64 字符串——太麻烦了;因此我想知道是否有更好的解决方案
  • 嗨,不,我没有找到答案:/

标签: angular svg angular-library ng-packagr


【解决方案1】:

我遇到了同样的问题,我发现的唯一决定是在“lib”部分“cssUrl”参数中包含ng-package.json

"lib": {
   "entryFile": "src/public-api.ts",
   "cssUrl": "inline"
 },

根据文档,它允许使用数据 URI 在 css 文件中嵌入资产。

【讨论】:

    猜你喜欢
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2019-02-09
    • 2019-05-04
    • 2011-09-29
    • 2015-01-21
    相关资源
    最近更新 更多