ng-packagr创建Angular组件库

1、安装  node.js

2、全局安装cli: 

npm install -g @angular/cli

或者

yarn global add @angular/cli

3、新建项目

ng new my-component-library

my-component-library 为新建的项目名

4、运行

ng serve  默认端口4200

或者

ng serve --port 1200   // 设置你喜欢的端口

5、在app文件夹下新建组件

创建 header 模块:

ng generate module modules/header

创建 header 组件:

ng generate component modules/header

打开 header.component.html 文件,并替换为如下内容:

<h1>
  <ng-content></ng-content>
</h1>

打开 header.component.css 文件,并替换为如下内容:

h1 {
  color: red;
}

打开 header.module.ts 文件,并在 @NgModule 中添加 exports ,并导出 HeaderComponent

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HeaderComponent } from './header.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [HeaderComponent],
  exports: [
    HeaderComponent     // 导出组件
  ]
})
export class HeaderModule { }

打开 app.module.ts 文件,并导出 HeaderModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

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

6、一个简单的组件已经写好了,我们测试下

打开 app.component.html 并替换为如下内容:

<app-header>测试下,看看有什么变化</app-header>
运行 ng serve

7、下面我们开始使用ng-packagr打包了

首先我们在项目中安装  ng-packagr

npm install ng-packagr --save-dev

或者

yarn add ng-packagr

根据ng-packagr文档得知,我们需要在我们的项目中添加两个文件,ng-package.json 和 public_api.ts


在 ng-package.json 文件中添加如下内容:

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

在 public_api.ts 文件中导出 header.module.ts

内容如下:

export * from './src/app/modules/header/header.module'

在 package.json 文件中的 scripts添加 "packagr": "ng-packagr -p ng-package.json" ,告诉 ng-packagr 根据 ng-package.json 来打包我们的组件库。同时,设置 "private": false 。


运行 npm run packagr 创建组件包,创建完成后会在项目的根目录中生成 dist 文件夹,里面的内容就是我们生成的标准的 Angular 组件库的结构。

进入 dist 目录执行 npm pack打包组件库,打包完成后,会在项目的根目录生成 my-component-library-0.0.0.tgz0.0.0来至于 package.json 文件中一部分。

我们可以在应用中使用 npm install 安装本地的开发包。

8、发布

npm publish

可能有问题,我一般都是这么上传的



9、可能会遇到的问题

在打包的时候会出错

会要求将package.json里面的  dependencies 依赖删掉 

或者 将dependencies替换成peerDependencies


如此,ng-packagr就结束了

如有问题,请评论




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值