Ole
Ole

Reputation: 47232

Importing an SVG File in an Angular CLI Project?

It works fine in Stackblitz.

import circle from './circle.svg';

But when I try the exact same import in an Angular CLI project like this:

import logo from './logo.svg';

VSCode displays the error:

Cannot find module './logo.svg'.ts(2307)

And Angular displays the error:

    ERROR in src/app/app.component.ts(5,18): error TS2307: Cannot find module './logo.svg'.

Thoughts?

Upvotes: 3

Views: 3022

Answers (1)

Łukasz Nojek
Łukasz Nojek

Reputation: 1651

What worked for me was

const logo = require('./logo.svg') as string;

If it doesn't work, try:

const circle = require('!!raw-loader?!../assets/logo.svg') as string;

It will disable the default file loaders and return the file contents.

You can also import the file at runtime:

  constructor(http: HttpClient) {
    http.get('/assets/logo.svg', {responseType: 'text'})
      .subscribe(svg => console.log(svg));
  }

or use it as an image source:

<img src="logo.svg" />

Please note that your SVG won't work immediately as it has an invalid format. I had to add version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> to the <svg> tag to make it display:

<svg viewBox="0 0 104 104" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  ...
</svg>

Upvotes: 4

Related Questions