Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inline svgs in angular?

I'm trying to load svgs inline with angular 7.

So far I tried:

import icon = require('./icon.svg');

results in icon.svg due to file-loader

import icon = require('raw-loader?!./icon.svg');

results in __webpack_public_path__ + "icon.svg";

which is the same as:

import * as icon3 from 'raw-loader?!./icon.svg';

and

import icon4 from 'raw-loader?!./icon.svg';

will become undefined.

However renaming the icon.svg in something like icon.foo and then loading the icon with:

import * as icon from 'raw-loader?!./icon.foo';

and the appropriate type in typings.d.ts results in the anticipated behavior and the variable icon holds the inlined content.

For me it seams like the file-loader somehow precedes the raw loader. Changing node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/common.js to load svgs like htmls in the rules works as well. But this is not a way to go.

Any ideas?

like image 674
Eydrian Avatar asked Oct 19 '25 02:10

Eydrian


2 Answers

Because the rule is already defined, it has to be overruled by putting two !! at the beginning of the loader:

import icon = require('!!raw-loader?!./icon.svg');

ADDITION 2021

it should work without require ... do not forget the typings.d.ts

import icon from '!!raw-loader?!./icon.svg';

See: https://webpack.js.org/loaders/raw-loader/ at the very bottom

Beware, if you already define loader(s) for extension(s) in webpack.config.js you should use:

'!!raw-loader!./file.css'; // Adding !! to a request will disable all loaders specified in the configuration

like image 68
Eydrian Avatar answered Oct 21 '25 17:10

Eydrian


I would suggest you to create a .ts file

my-svg.ts

export const mySVG = `<svg></svg>`;

Then you can import it normally

import {mySVG} from 'path/to/file/my-svg.ts'
like image 24
Josef Katič Avatar answered Oct 21 '25 16:10

Josef Katič