How can images be used in an Angular Element

為{幸葍}努か 提交于 2019-12-09 22:46:51

问题


I am creating an angular element which is supposed to be embedded on multiple external sites.

The embedding process will ofc just be a reference to the compiled script and a DOM element representing the element:

<html>
   <head>
      <script src="element.js"></script>
   </head> 
   <body>
      <element></element>
   </body>
</html>

But the problem is that the element makes use of a few assets in .png, .svg, .gif and .jpg format.

And of course the compiled element used on a different site, cannot reference those resources.

The documentation for angular elements is very limited, and not even Angular Docs says anything about this.

What is the most optimal way to achieve this? I have seen some people who converted the resources to data and rendered it that way instead.


回答1:


The best way to create a fully self-contained component is to embed the images into the component using DATA URIs.

Instead of this:

<img src="http://www.example.com/image.jpg"/>

You would encode the image file into a text format, like Base64, and then use that text data in the src attribute:

<img src="data:image/png;base64,your-base-64-encoded-image-data" />

More details here: https://www.thesitewizard.com/html-tutorial/embed-images-with-data-urls.shtml

This does increase the size of your component but it is self contained and will be portable to other apps without needing to include the image as a separate file.

SVG files are already text, but they are XML based so you only need to URL encode the file and not Base64 encode it. This produces a much smaller chunk of data.

You can run Base64 command on a *nix machine:

base64 -i "myimage.jpg"

or:

base64 -i "myimage.jpg" -o "base64.txt"

Or use an online converter:

  • https://www.base64-image.de/
  • https://ezgif.com/image-to-datauri


来源:https://stackoverflow.com/questions/54708824/how-can-images-be-used-in-an-angular-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!