Home > database >  Angular: importing images as typescript modules
Angular: importing images as typescript modules

Time:12-09

In React (CRA), the following works: import logo from './logo.png';. However when I try this in Angular (12) I get the error Cannot find module './logo.png' or its corresponding type declarations.

I know the "angular way" is to make use of assets, however this doesn't work for me, since I'm creating an Angular library, which has no assets.

How can I make the above work or what are alternative solutions to solve this?

CodePudding user response:

In angular you can use ng-packagr to copy assets in the library build folder. ng-package.json file is already available in your library root folder.

  {
  "ngPackage": {
    "assets": [
      "CHANGELOG.md",
      "./styles/**/*.theme.scss"
    ],
    "lib": {
      ...
    }
  }
}

see this link for more details: https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md

CodePudding user response:

I converted the image to a base64 string. However when using this directly in the src I got an warning in the console about something to do with sanitizing.

After some searching, it turns out you need to sanitize your own resource strings using import { DomSanitizer } from '@angular/platform-browser';. Thanks to BASE64 to image angular 2.

Some notes: Use DomSanitizer with care since there could some risks. Make sure the data is trusted.

  • Related