Thursday, 13 October 2016

Publish angular 2 app to NPM

Prerequisites: Knowledge about angular 2 and it's configuration files.

First clone the project git@github.com:deshak9/Demo.git

1. First of all, we will look into JSearch, here I will just explain what require for publishing our library to NPM

2. About JSearch/src/jsearch.service.ts

  • A simple class
3. About JSearch/jsearch.ts
export {JSearch} from './src/jsearch.service';
  • This is the line which exports our library, which can be imported by other end developers like blow 

import { JSearch } from 'jsearch/jsearch';

4. About JSearch/package.json

"typings": "./jsearch.d.ts"
  • This line in package.json tell about the typings configuration so that compiler can perform autocomplete.

To test it locally, run following commands.

This command will download all dependencies
npm install

This command will compile all .ts files and generate .map, .js and .d.ts files
npm run app

This command will generate jsearch-1.0.0.tgz in root folder
npm pack

Now you should be able to see jsearch.js, jsearch.d.ts files in root folder along with jsearch.ts file


Now you are ready with your library to be published to NPM, but wait, first testing it locally will be great Idea.

So here you go

First of all run following commands,

npm install

Download our own library from local JSearch project
npm install ../JSearch/jsearch-1.0.0.tgz --save

You must see jsearch library in node_module directory.

1. We will go through JSearchTest

2. In JSearchTest/systemjs.config.js we have added this line so that we can import this library in our components
'jsearch' : 'npm:jsearch',

3. This change will ensure proper loading of jsearch library at the browser.

jsearch: {
    defaultExtension: "js"},


run the following command and you should see the message printed in you browser console

npm start


If everything goes right, run following command to publish your library to NPM server.

npm publish