我对AngularJS发布的Angular版本有些陌生,因此决定尝试一下。我想要做的是建立一个UI组件库,以及一个将使用该库的应用程序。在我的库中,我决定将这些组件创建为WebComponents,因此按照到目前为止找到的教程,我会得到类似的
import { Injector, NgModule } from '@angular/core'
import { createCustomElement } from '@angular/elements';
import { MyButtonComponent} from './my-button.component'
@NgModule({
declarations: [MyButtonComponent],
entryComponents: [MyButtonComponent]
})
export class MyButtonModule {
constructor(injector: Injector) {
const myButton = createCustomElement(MyButtonComponent, { injector });
customElements.define('my-button', myButton);
}
}
对于我的自定义组件。如果我将组件的所有文件(模块,组件,模板和SCSS文件)直接添加到我的应用程序中,它将按预期工作,因此我知道组件声明正确。但是,如果在我的应用程序中包括库中的组件,则在使用ng serve
运行我的应用程序时,我会看到错误:
Error: StaticInjectorError(AppModule)[MyButtonModule -> Injector]:
StaticInjectorError(Platform: core)[MyButtonModule -> Injector]:
NullInjectorError: No provider for Injector!
我正在使用Angular 6,并且两个项目都在本地运行,并且正在使用ng-packagr
捆绑我的库。我在图书馆中添加了@angular/core
和@angular/elements
作为peerDependencies
,在主应用程序中我必须添加
"resolutions": {
"@angular/core": "6.1.4"
}
解决错误cannot redeclare block-scoped variable 'ngDevMode'
(不确定是否相关)。最初,我认为注入错误可能是由this引起的,但是我已经将preserveSymlinks
添加到了angular.json
文件中,但仍然出现错误。
有什么想法会导致这种情况吗?
更新:如果我从库文件夹中手动复制文件,然后将其粘贴到主应用程序的node_modules
文件夹中,它将起作用,这使我认为它涉及符号链接。
答案 0 :(得分:1)
我遇到了同样的问题,我通过植入该帖子的解决方案解决了这个问题:https://github.com/jvandemo/generator-angular2-library/issues/277
发生问题时,将npm install命令本地应用到项目库文件夹时,npm创建该库的快捷方式,并出现错误。
另一种解决方案是您使用“ npm pack yourlibary”命令打包库,并使用npm install在目标项目中安装生成的文件
答案 1 :(得分:1)
要使用npm link
版本的库运行业力,需要在preserveLinks: true
(test
部分)builder-angular:karma
中添加angular.json
:
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"preserveSymlinks": true,
// ...