Use image asset in angular library

128 Views Asked by At

I have a couple custom libraries that I load dynamically at runtime based on configuration. I can use assets in an angular application, however this does not work in my library.

Dependency in my package.json

{
  ...
  "dependencies": {
    "custom-plugin": "1.0"
  }
  ...
}

That library is installed and available in my node_modules directory:

node_modules
  -- custom-plugin
     -- lib (angular module/components here)
     -- assets
       -- image.png

I would like to reference image.png in an html template. I have tried to reference this in an html template in my component as well as outside with no luck.

HTML template, none of these work

<img src="@node_modules/custom-plugin/assets/image.png" />
<img src="assets/image.png" />
<img src="/assets/image.png" />
<img src="src/assets/image.png" />

EDIT: Running Angular 9

Tried adding "assets" property to angular.json.

"projects": {
  "mylib": {
    "projectType": "library",
    "architect": {
      "build": {
        "builder": "@angular-devkit/build-ng-packagr:build",
        "options": {
          "tsConfig": "admin/tsconfig.lib.json",
          "project": "admin/ng-package.json",
          "assets": ["src/assets"]
        },

However when building I get the following error:

Schema validation failed with the following errors: Data path "" should NOT have additional properties(assets)

2

There are 2 best solutions below

0
androbin On

Any folder can be added to the assets configuration. See the documentation

Add the @node_modules/custom-plugin/assets/ folder.

  {
    "glob": "**/*",
    "input": "@node_modules/custom-plugin/assets/",
    "output": "/custom-plugin-assets/"
  }
2
mounds On

An Angular Library (which your project is) requires different config to that of an Angular Application to include assets.

You need to add an 'assets' element at the root of your ng-package.json file (not the angular.json file). From there you have a few options for how to include assests:

  1. A string of the rel path to the file (you can use wildcards)
  2. an object containing an input, glob, and output property so you have more control over the final destination of the asset.

E.g.

{
  "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
  "dest": "../../dist/my-lib",
  "lib": {
    "entryFile": "src/public-api.ts"
  },
  "assets": [
    "node_modules/rxjs/CHANGELOG.md",
    { "input": "node_modules/rxjs", "glob": "CHANGELOG.md", "output": "rxjs-assets" }
  ]
}

Building this lib gives me this:

enter image description here

This is documented here: https://github.com/ng-packagr/ng-packagr/blob/main/docs/copy-assets.md

Once you have the asset exported where you want it, you should be able to reference it in your angular application as you normal would.