As you’re doing your initial planning of your Angular architecture, you may find that one of your shared resources needs to be shared across multiple apps. You want to put it up in npm, for instance, or maybe in an internal npm that your company may use. That way, multiple applications could take advantage of it. Sounds good? Yes, sounds great 😊.
To get started, you’ll first need to create a new project using the CLI.
We should be all good at this point. From here though, we need to use a command that the CLI provides in Angular 6 or higher, which is ng generate. This ng generate library is designed to create a custom shared library. Then, by giving your library a name, it will be added to a separate project, which is called a workspace.
When you do ng new you get a workspace with one project in it, which is your web project. This ng generate will add a second version into the workspace so that we can actually test out our library in the Angular app without publishing to npm or any other resource. Now, this modifies the tsconfig file and that’s going to be updated so that the Angular project, the separate one in the workspace, understands how to get to the library, the shared library that we’re going to be building.
Then you can build your library using the ng build command and then give it the name of your project, like this:
You can use this and test it directly in the other Angular project that’s within your workspace. So, it makes it really easy to do this without having to publish into npm somewhere. After that, we would want to publish to npm once we’re ready to go, we’ve tested it out and it looks good, because we want to be able to pull in from npm, whether it’s the npm that’s just out there that anybody can get to, or if it’s an internal npm you may have at your company. We want to pull from those into our different applications so we can get reuse.
We need to do this to go into the dist folder and there will be a package.json file included. That’s going to be used to then publish up to npm. We only need to write the following command:
So, should we see how things are different in our solution? Let’s go ☺.
#angular-cli #customlibrary #angular #typescript