[英]How can I get my build toolchain to resolve `src` references in an Angular2 inline template?
I'm writing a simple Angular2 component: 我正在编写一个简单的Angular2组件:
@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
. 我使用的webpack配置与官方文档非常相似,因此
.component.ts
文件通过awesome-typescript-loader
传递。 When I build the project, this component winds up with <img id="logo" src="../img/logo.png">
in the page, ie the image URL isn't rewritten by Webpack. 当我构建项目时,该组件在页面中显示为
<img id="logo" src="../img/logo.png">
,即,Webpack不会重写图像URL。 I believe this is because inline templates aren't being parsed for src
properties. 我相信这是因为没有为
src
属性解析内联模板。
I have tried working around this by doing an explicit require()
: 我尝试通过做一个明确的
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..."
. 这似乎是很多额外的工作,但确实可以完成工作-图像以
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. 自动修复源会很好,但是还有一个更大的问题:当Webpack不进行解析时,分配将通过Angular的DOM清理器进行,并且SVG图像会以
unsafe:
为前缀unsafe:
这意味着它们不会被渲染在浏览器中。 I see a workaround that involves de-sanitizing the string but it kind of seems like a hack. 我看到了一种解决方法,其中涉及对字符串进行消毒处理,但似乎有点像hack。 I'd avoid all this if I could get Webpack to just rewrite my inline template for me.
如果可以让Webpack为我重写内联模板,我会避免所有这些情况。
Use html-loader to teach webpack html-style "imports". 使用html-loader来教webpack html样式的“导入”。
I have something like this in my webpack.config.js
: 我的
webpack.config.js
有这样的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']
}
PS: I don't remember if or why I had to specify this: PS:我不记得是否或为什么必须指定以下内容:
?root=assets&attrs[]=img:src&attrs[]=image:src&attrs[]=image:xlink:href
so maybe try seeing what's that first :) 所以也许先看看那是什么:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.