gpt4 book ai didi

angular - 如何编写 Angular2 npm 模块 - Angular2 RC 6

转载 作者:太空狗 更新时间:2023-10-29 17:20:41 28 4
gpt4 key购买 nike

我不知道如何为 angular2 编写 npm 模块。
尽管我找到了 2 个教程(OneTwo),但没有一个介绍如何将 angular2 模块 (@NgModule) 实现为 npm 包。

我不明白的是,我到底什么时候需要注入(inject)像 BrowserModule 这样的模块?我什至必须将它与我的模块一起注入(inject),还是仅注入(inject)指令就足够了?

到目前为止我的插件:
- https://github.com/yves-s/ng2-flexbox-grid/tree/develop
- https://www.npmjs.com/package/ng2-flexbox-grid

目前它是@btmorton 的 angular2-grid 的 RC6 副本和更新。

但我无法让它工作。

更新:

这是我模块的当前状态 ng2-flexbox-grid.ts

export * from './src/directives';
export * from './src/components';
export * from './src/interfaces';

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';

import {NgGrid, NgGridItem} from './src/directives';

const mapValuesToArray = (obj) => Object.keys(obj).map(key => obj[key]);
// const directives = mapValuesToArray(directiveItems);

export default {
directives: [NgGrid, NgGridItem]
}

@NgModule({
declarations: [],
imports: [
BrowserModule,
CommonModule
],
exports: [NgGrid, NgGridItem]
})
export class Ng2FlexboxGridModule {}

更新 - 解决方案

在@Clint 的帮助下,我可以把那个 child 带回家。

可能最大的问题是我不知道 @NgModule 究竟是如何工作的。我很确定如果我仔细阅读 @NgModule docs 会有帮助

重要的部分是声明和导出模块指令。这样,您只需导入 FlexboxGridModule 即可使用它导出的指令。

导出:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {NgGrid, NgGridItem} from './src/directives';

@NgModule({
imports: [BrowserModule],
declarations: [NgGrid, NgGridItem],
exports: [NgGrid, NgGridItem]
})
export class FlexboxGridModule {}

导入:

import {NgModule}      from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AppComponent} from './app.component';
import {FlexboxGridModule} from "ng2-flexbox-grid";

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

最佳答案

当你制作一个模块时,你应该确保它导入模块并声明它使用的组件,以及导出任何应该对消费者可用的东西。例如:

@NgModule({
imports: [...modulesImConsuming],
exports: [...modulesAndComponentsMyConsumersNeed],
declarations: [...myModulesComponents]
})

在您的实例中,我们会(注意 声明 更改):

@NgModule({
declarations: [NgGrid, NgGridItem],
imports: [
BrowserModule,
CommonModule
],
exports: [NgGrid, NgGridItem]
})

然后要使用我们的模块,我们只需要导入它。导入模块时,我们可以访问所有组件(NgGridNgGridItem)以及导出的任何模块(以及导出模块导出的所有内容,等等)。在您的情况下,我们将:

@NgModule({
imports: [FlexboxGridModule]
})

关于angular - 如何编写 Angular2 npm 模块 - Angular2 RC 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39321380/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com