How to publish Angular component to NPM
There are some requirements that a module needs to fullfil before it can be published to npm. For example, you’ll need a main field in your package.json https://docs.npmjs.com/about-packages-and-modules. Plus, Angular is running typescript, which requires some extra steps to compile it to javascript. So it is easier to use ng-packagr to help with the process.
This is based on my published ItemsTextBox angular component in npm https://www.npmjs.com/package/items-text-box, repository available on github - https://github.com/thecodinganalyst/NgItemsTextBox.
Documenting my steps over here:
- Install
ng-packagrin the devDependenciesnpm install ng-packagr --save-dev - Create the
ng-package.jsonfile in the top folder with the following content.{ "$schema": "./node_modules/ng-packagr/ng-package.schema.json", "lib": { "entryFile": "public_api.ts" } } - Create the
public_api.tsfile in the top folder with the following content.Note that the path should link to the module.ts file, but you omit the
.tsextension. In the below example, the module which I want to publish is not the main app.module.ts, but i created a module in themodulesfolder.export * from './src/app/modules/item-text-box/item-text-box.module'; - Create the
packagrcommand in thepackage.json(so that you can easily run the ng-packagr to build your npm compatible package), and set theprivateproperty tofalse"scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "packagr": "ng-packagr -p ng-package.json" }, - Run the
packagrcommand, to package the module you want to publish into thedistfolder.npm run packagr - Go into the
distfolder, andnpm packto create the tar ball for distribution.cd dist npm pack - Create an account on https://www.npmjs.com/ if you haven’t. Login to your npm account from the command line.
npm login - Publish your module, then head over to your npm page to see the updates.
npm publish