user2010955
user2010955

Reputation: 4011

Best way to create an angular 4 library

what's the best way to create an angular library ? I'd like to create some libraries to be added in my angular projects, providing common-case services, like a RestService to perform rest calls, AuthService for authentication, and some components too, (e.g ). The library should be distribute as an npm package.

Should I create the library "by hand", handling module loader/bundler, testing framework, typings etc, or I can go straight with angular/cli as explained here ?

Any comments?

Thanks

Upvotes: 2

Views: 1192

Answers (2)

moryR
moryR

Reputation: 76

There is an unofficial tool by David Herges named ng-packagr.

  • first install this package: npm install ng-packagr

  • After installing add a file named ng-package.json to the root of your project. and edit it as bellow:

{
  "$schema": "./node_modules/ng-packagr/package.schema.json",
  "ngPackage": {
    "lib": {
      "entryFile": "public_api.ts"
    }
  }
}

  • add this line of code to your packag.json file "scripts" property:

"packagr": "ng-packagr -p ng-package.json"

  • add this public_api.ts file to the route of your project and export the module in this file for example:

export * from './src/app/modules/sample.module';

  • When your module is ready just run this command: npm run packagr

a dist folder would be generated in your project.

  • change directory into dist folder.

  • npm login to enter your npmjs account

  • npm publish to publish the version of the module which is mentioned in your package.json

Notice to export all needed components and services in your module.

Upvotes: 2

Ryan Diehl
Ryan Diehl

Reputation: 51

We have had good luck leveraging a starter project such as https://github.com/thakurinbox/angular-library-starter

All the boilerplate stuff is taken care of by the starter, and you simply add your code. (Admittedly that particular starter does not have Karma configuration for unit testing, but that was fairly trivial to add).

Upvotes: 2

Related Questions