How to find img tag in angular 7

十年热恋 提交于 2019-11-27 16:31:32

In order to do this, we will need to execute a Node script that will search for any image URL inside the HTML & CSS files using Regex. After that, it will replace these URLs with their Base64 values.

First thing, we need to install these NPM packages that will make our life easier:

npm install replace-in-file --save-dev
npm install datauri --save-dev

We will use the first one to find the images URLs, and the second one to convert the images onto Base64.

After installing these packages, we will create a Node script file contains the following:

const dataUri = require('datauri').sync;
const replace = require('replace-in-file');

const replaceOptions = {
  // Files to search. For now, we need HTML and CSS
  files: ['./dist/LIBRARY_NAME/**/*.js', './dist/LIBRARY_NAME/**/*.html'],
  // Don't search inside these folders / files 
  ignore: [],
  // Search for URLs using this Regex. It supports "./" prefix and the png / jpg files
  from: /\.\/|assets.*\.(png|jpg)/gm,
  // Replace the match with the Base64 value using dataUri
  to: match => { return match === './' ? '': dataUri(match) },
};

replace(replaceOptions)
  .then(results => {
    console.log('Replacement results:', results);
  })
  .catch(error => {
    console.error('Error occurred:', error);
  });

After that, we need to run the script after the build of the library. This can be done by adding this to package.json:

build: "ng build LIBRARY_NAME && node MY_SCRIPT_NAME.js"

Then, you can run the build and script using:

npm run build

UPDATE

There is a property you can add it to the ng-package.json to convert the CSS image URLs into Base64

 "lib": {
  "cssUrl": "inline"
 }

More info can be found here.

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