0

I'm writing a simple Angular2 component:

@Component({ ...,
  template: `
    <img id="logo" src="../img/logo.png">
  `, ...
})

I'm using a webpack config very similar to the official docs so the .component.ts file is being passed through awesome-typescript-loader. When I build the project, this component winds up with <img id="logo" src="../img/logo.png"> in the page, i.e. the image URL isn't rewritten by Webpack. I believe this is because inline templates aren't being parsed for src properties.

I have tried working around this by doing an explicit require():

const SITE_LOGO = require("../img/logo.png");

@Component({ ...,
  template: `
    <img id="logo" [src]="logo">
  `, ...
})

export class AppComponent {
  logo = SITE_LOGO;
}

This seems like a lot of extra work, but it does get the job done -- the image winds up with src="data:image/png;base64...".

It'd be nice to have sources fixed up automatically, but there's a bigger issue: when Webpack doesn't do the parsing, the assignment goes through Angular's DOM sanitizer and SVG images get prefixed with unsafe: which means they don't get rendered in the browser. I see a workaround that involves de-sanitizing the string but it kind of seems like a hack. I'd avoid all this if I could get Webpack to just rewrite my inline template for me.

JeanJacques
  • 1,754
  • 1
  • 12
  • 25
Coderer
  • 25,844
  • 28
  • 99
  • 154

1 Answers1

0

Use html-loader to teach webpack html-style "imports".

I have something like this in my webpack.config.js:

{
    test: /\.html$/i,
    loader: 'html-loader?root=assets&attrs[]=img:src&attrs[]=image:src&attrs[]=image:xlink:href',
    exclude: ['./src/index.html']
}

P.S: I don't remember if or why I had to specify this:

?root=assets&attrs[]=img:src&attrs[]=image:src&attrs[]=image:xlink:href

so maybe try seeing what's that first :)

Amit
  • 4,274
  • 21
  • 25
  • This isn't going to help with inline templates, I don't think -- I do have some components that load the template from a URL source and I think those are working. – Coderer Aug 07 '17 at 14:04
  • Hmm true, but I think avoiding inline templates is a good enough idea as it is :) especially if it solves your issue along with `html-loader`. – Amit Aug 07 '17 at 14:05
  • I had to add `html-loader` to my webpack config to get external templates working, but that broke the `<%= require(...) %>` that I had in my index.html. `exclude` wasn't working for some reason so I changed the `test` to `/\.component\.html$/`. I'd still like some kind of fix that allows me to use inline templates for very short components... – Coderer Aug 07 '17 at 14:11
  • That's the limit of my experience with the issue then :) Good luck! – Amit Aug 07 '17 at 14:12