Create Angular Library

  1. ng new weather –createApplication = false
  2. ng generate library weather

    It will create & update 3 files

    weater-src-lib-public_api.ts

    “/lib/” [weather.service, weather.component, weather.module]

  3. ng generate application weathertest
  4. In “agngular.json” new two projects added. “Projects” : {weather, weathertest}
  5. In “package.json” new added “ng.packager” : “4.2.0”

  6. In “tsconfig.json” added reference library output directory. “path”: {“weather”:dist/weather, “weather/*” : “dist/weather/”}
  7. import two modules in “weather.modules.ts”

    HttpClientModule, CommonModule

  8. Add script in package.json to build our library

    “script”:{“weatherbuild”: “ng build weather”}

    :> npm run weatherbuild

    Output will be in “dist” directory

Test our library within our test application project

  1. Inside wethertest folder import our weather module from weather folder remeber the “tsconfig” path entry is helping to resolve “dist” directory.

    weathertest-app.module.ts import {weatherModule} from “weather”

  2. In appcomponent add our component tag with required input
  3. Test the app with “ng serve weathertest”

3 Ways to use the library in your project

1. Package the library

  1. Go to library bulder directory “cd dist/weather”
  2. Type:> npm pack

    Output : a new “taz” file will be created

  3. Now we can install library using npm install passing this package URL

    “npm install ./dist/weather/weather-0.0.1.tgz”

  4. We can see package has been installed using file url in “package.json”.

    “weather”:”file:dist/weather/weather-0.0.1.tgz”

  5. remove path from “tsconfig.json” (“weather”:”dist/…”)
  6. Build our app : ng buld weathertest
  7. run the app with simple http server

    dist-weathertest

    cd dist/weathertest/

    http-server

2. We can publish our library to npm, we can use private npm repo called “verdaccion”

Reference

Leave a Reply

Your email address will not be published. Required fields are marked *