我不知道如何为angular2编写一个npm模块。
尽管我找到了2个教程(1,2),但没有一个涉及如何将angular2模块(@NgModule
)实现为npm包。
我不明白的是,我到底什么时候需要像BrowserModule
一样注入模块?我甚至必须注入它与我的模块,还是仅仅注入指令就足够了?
My Plugin so far:
——https://github.com/yves-s/ng2-flexbox-grid/tree/develop
——https://www.npmjs.com/package/ng2-flexbox-grid
目前它是@btmorton的angular2-grid的拷贝和更新到RC6
但是我不能让它工作。
更新:
这是我的模块ng2- flexboxgrid的当前状态。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 {}
UPDATE - Solution
在@Clint的帮助下,我可以把孩子带回家。
可能最大的问题是我不知道@NgModule
到底是如何工作的。我很肯定,如果我仔细阅读了@NgModule
文档,它会有所帮助的
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]
})
在你的例子中,我们会(注意declarations
的变化):
@NgModule({
declarations: [NgGrid, NgGridItem],
imports: [
BrowserModule,
CommonModule
],
exports: [NgGrid, NgGridItem]
})
然后,为了使用我们的模块,我们只需要导入它。当导入一个模块时,我们可以访问导出的所有组件(NgGrid
, NgGridItem
)以及任何模块(以及导出模块导出的所有内容等等)。在你的情况下,我们将使用:
@NgModule({
imports: [FlexboxGridModule]
})
@NgModule和npm package有不同的用途。@NgModule是angular2用来动态封装和加载指令或过滤指令的工具。
Npm package是一个以统一的方式打包和分发代码的工具。这两者(npm和NgModule)之间没有任何关系。
我建议你先在不关心Npm的情况下编写你的NgModule,然后在你的应用中测试它。一旦它工作好了。然后你可以把你的模块作为npm包发布。
不应该两次导入BrowserModule
。你只需要在AppModule中导入它,如下所示:我假设你希望你的npm模块能够延迟加载。