简体   繁体   English

如何在Angular应用程序中链接到本地​​SVG文件?

[英]How to link to a local SVG file in the Angular app?

I'd like to replace a Clarity framwork icon with my own, using a local SVG file. 我想使用本地SVG文件将Clarity框架图标替换为我自己的图标。 I prepared a service for that: 我为此准备了一项服务:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class IconServiceService {

  icons: any = {
    'caret': '<svg viewBox="0 0 100 100"><use xlink:href="file://help.svg#caret"></use></svg>',
  };

  constructor() { }

  public load() {
        window['ClarityIcons'].add(this.icons);
  }
}

It works when instead of the <use xlink:href="file://help.svg#caret"> part I put the whole SVG content. 当我放置整个SVG内容而不是<use xlink:href="file://help.svg#caret">部分时,它会起作用。 However, when I want to link to a local file (like shown in the code) I cannot get the file. 但是,当我想链接到本地​​文件时(如代码中所示),我无法获取该文件。 I'm using Angular 7. How can I use the local SVG file here? 我正在使用Angular7。如何在此处使用本地SVG文件?

TypeScript can't load a file like SVG file directly. TypeScript无法直接加载SVG文件之类的文件。 Assuming you are using the Angular CLI, then you can just piggy back on the raw-loader that is part of the Webpack build process like so below to import the raw string and assign it to your variable. 假设您使用的是Angular CLI,那么您可以背负Webpack构建过程中的raw-loader ,如下所示,以导入原始字符串并将其分配给您的变量。

import * as CaretIcon from 'raw-loader!./path/to/file.svg';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class IconServiceService {

  icons: any = {
    'caret': CaretIcon,
  };

  constructor() { }

  public load() {
        window['ClarityIcons'].add(this.icons);
  }
}

If you aren't using the CLI or Webpack, you can follow these instructions that would apply for SVG files the same way (just substitute the svg in for html). 如果您不使用CLI或Webpack,则可以按照以下说明以同样的方式适用于SVG文件(仅将svg替换为html)。 https://medium.com/@sampsonjoliver/importing-html-files-from-typescript-bd1c50909992 https://medium.com/@sampsonjoliver/importing-html-files-from-typescript-bd1c50909992

Solution worked for me 解决方案对我有用

let icons = require('!raw-loader!../../../styles/assets/icons/icons.svg');

https://github.com/angular/angular-cli/issues/3879#issuecomment-358920021 https://github.com/angular/angular-cli/issues/3879#issuecomment-358920021

you may need declare const require: any; 您可能需要declare const require: any;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM