静态文件的相对路径,如images/css/js等



我有/src/app/some-module/some-componentsrc/public/images/user.png的文件夹结构。现在,当我愿意在我的某些组件中显示图像时,我必须将路径作为../../../public/images/user.png,这似乎太天真了,一旦图像数量增加,就会浪费精力。

我们在angular2中是否有一个路由机制或相对路径来提供静态文件?我正在使用Angular2的webpack.

这取决于你的base href看起来像什么

例如:

<base href="/src/">
无论你的组件模板在哪里,你都可以很容易地在下面使用

<img src="public/images/user.png" />

希望这有帮助!!

如果您使用WebPack,它会在构建过程中处理路径。<img src="...">需要指向文件在项目中的物理位置,相对于使用它的模板。

例如,在我的例子中,没有WebPack,它将是

<img src="img/rhamt-square-248.png" width="172">

因为img/直接在应用根目录下。

而对于WebPack,这是有效的:

<img src="../../../img/rhamt-square-248.png" width="172">

否则会得到如下编译错误:

./src/app/misc/about.component.html中出现错误
模块未找到:错误:无法解析'/home/ondra/work/Migration/windup-web/ui/src/main/webapp/src/app/misc'中的'./img/rhamt-平方248.png'
@ ./src/app/misc/about.component.html:402-439
@。/src/app/misc/about.component.ts
@。/src/app/app.module.ts
@/src/main。ts

最新更新