DEV Community

John Peters
John Peters

Posted on • Updated on

Angular Libraries : Refactor Existing Components into a Shared Module

When we read Angular's documentation on refactoring components into libraries, we find that it's short on theory and long on warnings.

The reason is that creating our own custom modules is more simple than refactoring existing code.

Even though we know better, our code is laced with outside dependencies that were caused by close coupling concerns.

This problem is not unique to Angular, Typescript or JavaScript. It's a problem in every framework and every language.

If we have not started with reusable components and then attempt to refactor into that architecture, we are in for a major effort in getting it done.

Its not hard to do, it's just time consuming. We will let the compiler guide us.

Don't forget to bring the tests along!

Consider this:

Alt Text

In the folder

  project/angular-library/src/lib/components
Enter fullscreen mode Exit fullscreen mode

We copied existing angular components (to be reused) and pasted them here.

Then we compiled from the "projects" folder with

ng build angularLibrary 
Enter fullscreen mode Exit fullscreen mode

The name angularLibrary was in our angular.json already.

Bad news

The compile failed miserably.

🍋🍋🍋🍋🍋

As expected we had major dependency issues.

The Real Work Starts

  • The first thing we found was that there were no necessary NPM packages in the library solution.

  • Because the app.module of the real app is not in our library, none of the dependencies are in full view. It's better to solve dependency issues based on compiler errors, than to just copy the app.module file over.

  • We installed only necessary node packages and went through the typical painful NPM install process for each of them. We found that even imported packages don't fully list their own dependencies and sometimes even npm audit fix wouldn't work etc.

  • We kept asking, which package.json does the library use as there are two. The outer package.json is for the build and the inner one is for the consumer who can run a npm install.

  • The inner package.json is an extension of the outer one. Don't add packages to the inner one until we get the build running. We'll discuss the inner package.json file in a npm publishing article.

Alt Text

Does this folder structure look more familiar?

Summary

So far the Angular documentation was correct but poorly introduced. Their example showed how to create a library which doesn't experience dependency issues at first compile.

They didn't tell us how to add existing components in.

Next: Part 2 of the "Why is this so difficult to do series"

JWP 2020 Angular Libraries "Adding new components via copy and paste"

Top comments (0)