How can images be used in an Angular Element

2019-04-13 13:38发布

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条回答
干净又极端
2楼-- · 2019-04-13 14:34

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:

查看更多
登录 后发表回答