Add Angular Material to a custom library

Mordechai Dror picture Mordechai Dror · Nov 18, 2018 · Viewed 8.7k times · Source

I want to write my own library and reuse it in other projects, so I created a new app and generated a library there:

ng new lib-collection
cd lib-collection
ng g library first-lib --prefix va

How to add Angular Material to my library? I wanted to use something like this:

ng add @angular/material --project=first-lib

But I got an error: Could not find the project main file inside of the workspace config (projects/first-lib/src). What's wrong?

Answer

smnbbrv picture smnbbrv · Nov 18, 2018

You don't need to add it there.

You need to add it to your primary application:

ng add @angular/material

Then add "@angular/material" to the peerDependencies of the projects/first-lib/src/package.json (just copy a line with @angular/material from your primary package.json).

What you just did:

  1. You installed the library to the primary package.json and can now run your code locally, because locally angular cli would use the primary package.json and node_modules
  2. You set it as a library's dependency and after you publish it and install at another place it will ask you to also install the peerDependencies there (as npm warning)

You can, of course, also add it to dependencies instead of peerDependencies and get it automatically installed with your library, but this is not a good way of managing frontend dependencies (but could be still good for pure node.js packages)