angularng-packagr

How to build and consume an Angular 18 library


The project I'm working on needs to split some components into a shared library. I'm using Angular 18 with standalone components. I've found a lot of answers / articles for these issues online, but none seem to actually answer my question or fix the build issues.

I'm starting this experiment with new, mostly empty Angular projects just to see if I can get it to work, before doing this with the actual project code.

Ideally this will end up living in a private NPM repo or maybe git somewhere.

Here's what I've done (names aren't great, sorry):

Create a new folder called "test", then cd into it. cd test

Create lib workspace. ng new lib cd lib

Create library project. ng g library test-lib

The generate command adds an example component, so I'll use that to test with. I'm not adding anything else to the library at this time.

Build library. ng build

Pack library. cd projects/test-lib npm pack This creates test-lib-0.0.1.tgz.

Now, back in the parent test directory, add another test project to consume the lib. ng new test cd test

Install local library module: npm i {path-before-test}/test/lib/projects/test-lib -S (I've also tried {pah-before-test}/test/lib/projects/test-lib/test-lib-0.0.1.tgz directly) I can see that the files from the packed library are in node_modules.

Now, in app.component.ts of this test project, try to import the component from the lib. import { TestLibComponent } from 'test-lib'; This results in a linting error on test-lib: Cannot find module 'test-lib' or its corresponding type declarations.

I've tried some hacky things with tsconfig.js and tsconfig.app.js as found in other answers for similar issues, but one, they don't seem like things I really want to change, like changing the target of the ts module. Also tried adding paths to the folders in node_modules and setting baseUrl to "./". These don't solve the problem.

I've also tried importing the component directly from test-lib/src/public-api. This removes the linting error, but results in an actual compile error: File 'node_modules\test-lib\src\public-api.ts' is missing from the TypeScript compilation.

What am I doing wrong?


Solution

  • Two issues here. First, ng build only builds the application, not the library. Basically you have two projects in the repository, the application and the library. And because you created the application first, it is the default project, if no project specified. To build the library, you need to specify the project by running ng build test-lib.

    Second, you are packing the source files, not the built library. Instead of packing projects/test-lib, you need to pack dist/test-lib.

    Further reading: https://angular.dev/tools/libraries/creating-libraries#publishing-your-library