로컬에서 Angular 라이브러리를 개발하는 방법

Nov 25 2022
안녕 ! 이 이야기에서는 로컬에서 Angular 라이브러리로 작업하는 방법과 원격 저장소로 지속적으로 푸시할 필요 없이 라이브러리를 개발하는 방법을 보여드리고 싶습니다. DRY - 코드 반복을 피하는 방법 크고 복잡한 Angular 프로젝트에서 작업하는 경우 , 코드 중복 문제에 직면하게 될 것이라고 확신합니다. 예를 들어 응용 프로그램의 "모양"에 초점을 맞추겠습니다. 모든 페이지에는 일관된 스타일이 있어야 합니다.
Unsplash의 Ryunosuke Kikuno 사진

안녕 ! 이 이야기에서는 로컬에서 Angular 라이브러리를 사용하는 방법과 이를 원격 저장소로 지속적으로 푸시할 필요 없이 개발하는 방법을 보여드리고자 합니다. :)

DRY - 코드 반복을 피하는 방법

크고 복잡한 Angular 프로젝트에서 작업하는 경우 코드 중복 문제에 직면하게 될 것이라고 확신합니다. 예를 들어 응용 프로그램의 "모양"에 초점을 맞추겠습니다. 모든 페이지에는 일관된 스타일이 있어야 합니다. 좋습니다. 간단합니다. 일반적인 스타일을 styles.scss파일로 이동하거나 7-1 패턴 을 사용하여 우아한 방식으로 디자인할 수 있습니다.

그러나 보기만 아니라 동작도 동일해야 하는 몇 가지 공통 구성 요소 가 있는 경우에는 어떻게 해야 합니까? 그것은… 여전히 쉽습니다! 응용 프로그램에서 공유 모듈을 만들고 거기에서 구성 요소를 정의하고 모듈 정의에서 내보내십시오. 엄청난 !

이제 더 복잡한 문제에 초점을 맞추겠습니다. 회사에 하나 이상의 Angular 애플리케이션이 있는 경우 어떻게 합니까? 각 애플리케이션은 다음과 같이 유사해야 합니다.

  • 같은 머리글과 바닥글을 가지고
  • 동일한 회사 CSS 스타일 지정
  • 양식, 유효성 검사 오류 및 기타 메시지를 표시하는 동일한 방법이 있습니다.

라이브러리 생성

여기 에서 라이브러리 생성에 대한 공식 문서 페이지를 찾을 수 있습니다. 여기에 설명된 단계를 따라 라이브러리를 생성해 보겠습니다.

ng new my-shared-workspace --no-create-application
cd my-shared-workspace
ng generate library my-buttons

  • my-shared-workspace 는 라이브러리의 공통 작업 공간입니다.
  • my-buttons 는 다른 프로젝트에서 재사용할 수 있는 예제 라이브러리입니다.

{
  "name": "@my-company/my-buttons",
  "version": "0.0.1",
  "peerDependencies": {
    "@angular/common": "^14.2.0",
    "@angular/core": "^14.2.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  }
}

my-shared-workspace/projects/my-buttons/src/lib> ng g c fancy-button

컴포넌트가 생성되었으므로 템플릿을 업데이트하여 버튼을 표시할 수 있습니다.

<button>fancy-button works!</button>

@NgModule({
  declarations: [
    MyButtonsComponent,
    FancyButtonComponent
  ],
  imports: [
  ],
  exports: [
    MyButtonsComponent,
    FancyButtonComponent // <-- here
  ]
})
export class MyButtonsModule { }

/*
 * Public API Surface of my-buttons
 */

export * from './lib/my-buttons.service';
export * from './lib/my-buttons.component';
export * from './lib/my-buttons.module';
export * from './lib/fancy-button/fancy-button.component'; // <-- here

라이브러리가 이미 생성되었으므로 이제 클라이언트 애플리케이션을 사용할 차례입니다. Angular CLI를 사용하여 생성 하고 애플리케이션의 종속성(마지막 종속성, 이후 ) 에 ng new my-application추가할 것 입니다.@my-company/my-buttonspackage.jsonzone.js

{
  "name": "my-application",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^14.2.0",
    "@angular/common": "^14.2.0",
    "@angular/compiler": "^14.2.0",
    "@angular/core": "^14.2.0",
    "@angular/forms": "^14.2.0",
    "@angular/platform-browser": "^14.2.0",
    "@angular/platform-browser-dynamic": "^14.2.0",
    "@angular/router": "^14.2.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4",
    "@my-company/my-buttons": "0.0.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.2.6",
    "@angular/cli": "~14.2.6",
    "@angular/compiler-cli": "^14.2.0",
    "@types/jasmine": "~4.0.0",
    "jasmine-core": "~4.3.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.7.2"
  }
}

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyButtonsModule } from '@my-company/my-buttons';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MyButtonsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

<lib-fancy-button></lib-fancy-button>

Error: src/app/app.component.html:1:1 - error NG8001: 'lib-fancy-button' is not a known element:
1. If 'lib-fancy-button' is an Angular component, then verify that it is part of this module.
2. If 'lib-fancy-button' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

1 <lib-fancy-button></lib-fancy-button>
  ~~~~~~~~~~~~~~~~~~

  src/app/app.component.ts:5:16
    5   templateUrl: './app.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component AppComponent.




** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

다음과 같은 추가 오류도 표시됩니다.

Error: src/app/app.module.ts:3:33 - error TS2307: Cannot find module '@my-company/my-buttons' or its corresponding type declarations.

3 import { MyButtonsModule } from '@my-company/my-buttons';

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@my-company%2fmy-buttons - Not found
npm ERR! 404
npm ERR! 404  '@my-company/[email protected]' is not in this registry.
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
Npm link to the rescue

여기에서 완전한 npm 링크 명령 설명서 를 찾을 수 있습니다 . 이 명령을 사용하여 라이브 다시 로드와 함께 로컬에서 공유 라이브러리를 개발하는 방법을 보여 드리겠습니다.

my-shared-workspace디렉토리 로 돌아가서 my-buttons라이브러리를 빌드하고(플래그 --watch는 실시간 재로드를 담당함) 빌드 디렉토리로 이동합니다.

my-shared-workspace> ng build my-buttons --configuration development --watch
Building Angular Package

------------------------------------------------------------------------------
Building entry point '@my-company/my-buttons'
------------------------------------------------------------------------------
✔ Compiling with Angular sources in Ivy full compilation mode.
✔ Writing FESM bundles
✔ Copying assets
✔ Writing package manifest
✔ Built @my-company/my-buttons

------------------------------------------------------------------------------
Built Angular Package
 - from: /Users/<user>/<path>/my-shared-workspace/projects/my-buttons
 - to:   /Users/<user>/<path>/my-shared-workspace/dist/my-buttons
------------------------------------------------------------------------------

my-shared-workspace> cd dist/my-buttons
my-shared-workspace/dist/my-buttons> npm link

added 1 package, and audited 3 packages in 1s

found 0 vulnerabilities

my-application디렉토리에서 이 링크된 라이브러리를 사용할 수 있도록 하는 angular.json옵션인 preserveSymlinks를 하나 더 추가합니다.

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "my-application": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/my-application",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "inlineStyleLanguage": "scss",
            "preserveSymlinks": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "my-application:build:production"
            },
            "development": {
              "browserTarget": "my-application:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "my-application:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "inlineStyleLanguage": "scss",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        }
      }
    }
  }
}

my-application> npm link @my-company/my-buttons

added 1 package, removed 1 package, and audited 918 packages in 2s

121 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

그 후 다시 실행 ng serve:

my-application> ng serve
✔ Browser application bundle generation complete.

Initial Chunk Files   | Names         |  Raw Size
vendor.js             | vendor        |   3.30 MB |
polyfills.js          | polyfills     | 318.02 kB |
styles.css, styles.js | styles        | 210.56 kB |
main.js               | main          |  12.32 kB |
runtime.js            | runtime       |   6.53 kB |

                      | Initial Total |   3.84 MB

Build at: 2022-11-24T18:27:00.803Z - Hash: 7669daf65ca2f665 - Time: 4598ms

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **


✔ Compiled successfully.

결과를 보자:

엄청난 ! 이제 fancy-button-component.html에서 무언가를 변경해 보십시오.

<button>fancy-button works - live reload!</button>

이제 불편함 없이 라이브러리와 어플리케이션 모두에서 작업하실 수 있습니다 :)

확인

사용 중인 라이브러리 버전을 확인하려면 다음 명령을 실행할 수 있습니다.

npm list -g
/usr/local/lib
├── @angular/[email protected]
├── @my-company/[email protected]+1669314745555 -> ./../../../Users/<user>/<path>/my-shared-workspace/dist/my-buttons

로컬에서 변경 작업을 마친 후 다음과 같은 방법으로 클라이언트 애플리케이션에서 연결된 라이브러리 사용을 중지할 수 있습니다.

my-application> npm unlink @my-company/my-buttons --no-save

my-shared-workspace/dist/my-buttons> npm rm -g @my-company/my-buttons

재료