Creating Library

4 분 소요

This Document Has Been Updated

Go Directly to the Updated Article

Leverage self-developed libraries within your Angular projects as if they were external dependencies.

Since Angular 6, ng-packagr has been officially supported, facilitating easy library creation. We recommend encapsulating frequently used functionalities into reusable, packageable libraries. This approach promotes code reuse and accelerates development workflows.

Library Generation

Utilize the Angular CLI to generate the library. Note that this process must occur within an existing Angular project. First, create a new project using ng new, and then execute the subsequent command to generate your library.

ng generate library [library-name]

This command creates a folder named library-name within the projects directory at the root of your Angular project.

Project Analysis

Examine the generated files to verify the integrity and structure of your newly created library.

Analyzing angular.json

Search for your project name within angular.json. The corresponding configuration block should have "projectType": "library". This configuration confirms that the project is correctly identified as a library.

"my-lib": {
  "projectType": "library",
  "root": "projects/my-lib",
  "sourceRoot": "projects/my-lib/src",
  "prefix": "lib",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-ng-packagr:build",
      "options": {
        "tsConfig": "projects/my-lib/tsconfig.lib.json",
        "project": "projects/my-lib/ng-package.json"
      }
    },

Analyzing package.json

Verify the presence of ng-packagr as a dependency within the library’s package.json file. This confirms that the required packaging tool is correctly configured.

Analyzing tsconfig.json

Determine the output location of your library’s build artifacts by inspecting the paths configuration in tsconfig.json.

"paths": {
  "my-lib": [
    "dist/my-lib"
  ],

Understanding File Roles

<package.json>

  • Enables distribution as an npm package.

<public_api.ts>

  • Serves as the entry file. It must include all files intended for export.
  • Even if exports are declared in a module, they must also be explicitly declared here.

<ng-package.json>

  • Configuration file for ng-packagr. Automatically generated by Angular CLI.

Library Implementation

Declare and export all components and other necessary files within your library.

Module Definition

import { NgModule } from '@angular/core';
import { MyLibComponent } from './my-lib.component';
import { FooComponent } from './foo/foo.component';

@NgModule({
  imports: [
  ],
  declarations: [
    MyLibComponent,
    FooComponent
  ],
  exports: [
    MyLibComponent,
    FooComponent
  ]
})
export class MyLibModule { }

Public API Definition (public_api.ts)

Specify the module and all exported file names from that module within public_api.ts. This ensures that the library exposes the intended components and services.

export * from './lib/my-lib.service';
export * from './lib/my-lib.component';
export * from './lib/my-lib.module';

Library Building

Build the library using ng build, similar to building a standard Angular project.

ng build my-lib

Upon successful execution, a dist/my-lib folder will be created, containing the compiled library files.

Package Generation

Navigate to the dist/my-lib directory and execute the package command to create the distributable package.

cd dist/my-lib

Public Package Creation

Create a public package using npm publish.

npm publish

If you are not logged into npm, a 401 error will occur.

The npm link command can be used to avoid reinstalling the library every time it is built during development.

Common Public Error

npm ERR! code E401
npm ERR! 401 Unauthorized - PUT https://registry.npmjs.org/my-lib - You must be logged in to publish packages.

npm ERR! A complete log of this run can be found in:

Private Package Creation

If you prefer a private package, use the npm pack command. This operates similarly to npm publish but does not require login and generates a .tgz file.

> npm pack

npm notice
npm notice package: my-lib@0.0.1
npm notice === Tarball Contents ===
npm notice 1.4kB esm2015/lib/my-lib.component.js
-- omitted --
npm notice 60B   lib/my-lib.service.d.ts
npm notice 118B  public-api.d.ts
npm notice === Tarball Details ===
npm notice name:          my-lib
npm notice version:       0.0.1
npm notice filename:      my-lib-0.0.1.tgz
-- omitted --
npm notice total files:   26
npm notice
my-lib-0.0.1.tgz

Automating Package Generation in package.json

For streamlined build and packaging, create scripts in package.json.

"scripts": {
  "build_lib": "ng build --prod my-lib",
  "npm_pack": "cd dist/my-lib && npm pack",
  "package": "npm run build_lib && npm run npm_pack"
},

Now, executing npm package will build and package the library in one step, generating a .tgz file.

Integration

To use the created library, install the package in the target project. For public packages, proceed as with any npm library. For private packages, first transfer the .tgz file to the project.

After transferring the file, install the .tgz file as you would a public package.

npm install ./my-lib

Verify that the module is installed in the node_modules folder.

Usage

The library can now be used in the project.

// app.module.ts
import { NgModule } from '@angular/core';
import { MyLibModule } from 'my-lib';

@NgModule({
  imports: [
  ],
  declarations: [
    MyLibModule
  ],
  exports: [

  ]
})
export class AppModule { }

Important Considerations

You cannot create a library project within an existing application project. It must be created as a separate project.

As of angular-cli v6.0.3, the following issues exist. These may be improved or changed depending on the version, so please keep this in mind.

  • Assets are not included when building the library. The asset folder must be copied manually.
  • Until this is resolved, copy the library’s assets to each project.
  • If the library uses scripts, they may not be applied. You must add the script code to the angular.json file of each project and execute it.

Reference Sites

댓글남기기