How To Create Angular Library

Create a workspace

ng new my-workspace --create-application=false

This will initialized a project without creating any app module and all.

Create a library

The following command will create a library.

ng g library @scope/my-library

The library source will be in

/my-workspace
	|-- projects
		|-- scope
			|--my-library
				|-- src
					|-- lib

You can skip the scope part if you don’t want and name your library like my-library

Build your library

Under /my-workspace directory run

npx ng build

This command will build all the projects in the workspace.

Note: You can specify a project using --project flag.

Output will be generated under /my-workspace/dist/scope/my-library directory.

Publish your library on NPM

You’ll need an account on npmjs.com. So get registered if you don’t have already.

  • Login to your account using the following command.

    npm login
    
       
     This will prompt for your credential.
    
    
  • Goto your library’s dist directory. Eg /my-workspace/dist/scope/my-library

  • Run

    npm publish --access public
    
       
     > Note: By default, npm publishes with **private access**. If you don't have the paid account which allows prive packages then it would fail.
    
    

Use Locally

  • Build the library and goto /dist/my-library

  • Create a symlink package using npm

    npm link
    
    
    
  • Go to your project where you want to use the library and install it using

    npm link my-library
    
    
    

It may happen that NgModule of your library may not work correctly with your angular project. To fix it add "preserveSymlinks": true to your project’s angular.json under projects.yourProject.architect.build.options