Angular Npm 包开发之踩坑小记3 | 更文挑战第22天

545 阅读2分钟

这是我参与11月更文挑战的第22天,活动详情查看:2021最后一次更文挑战

10. 报错关于 Cannot call a namespace ('moment')

错误信息如下

  Cannot call a namespace ('moment')

moment引进来赋值给一个常量即可

import * as moment_ from 'moment';

const moment = moment_;

参考

https://github.com/jvandemo/generator-angular2-library/issues/221#issuecomment-355945207

11. http拦截器不起作用

httpClientModule是http服务的模块,在项目中的某个懒加载模块再次引入的话会覆盖之前的http设置,这样注册在根模块的拦截器就会失效。
如果在npm包中配置了拦截器,用户项目中引入了http模块拦截器也会失效。

即最好保证httpClientModule在一个项目中只会被注入到module中一次。官方文档参考:

https://angular.io/guide/http#setup-installing-the-module

问题讨论: HTTP_INTERCEPTORS are reset when a lazy loaded module imports another module importing HttpClientModule

12. 在npm包的ngModule中使用xxx()导致报错Function calls are not supported

具体报错信息如下

Function calls are not supported in decorators but 'DndModule' was called.

解决方案

RouterModule是angular的路由模块, routes是自己配置的路由。 进行如下改写即可解决错误。

import { NgModule, ModuleWithProviders } from '@angular/core';

export const routerModuleForChild: ModuleWithProviders = RouterModule.forChild(routes)

@NgModule({
  imports: [
    routerModuleForChild
  ],
  ...
})

参考https://github.com/ng-packagr/ng-packagr/issues/778#issuecomment-385122626

13. 路由中懒加载引入npm包抛出模块报错

ERROR in Could not resolve module AuthModule relative to pages/pages.module.ts

之前的写法:

import {
  AuthModule
} from '@my/pages';

export const PagesRouting: Routes = [
  {
    path: 'auth',
    loadChildren: 'AuthModule'
  },
]

正确写法

import {
  AuthModule
} from '@my/pages';

export const PagesRouting: Routes = [
  {
    path: 'auth',
    loadChildren: () => AuthModule
  },
]

npm包中做路由懒加载也需要这样写。

参考https://github.com/aspnet/JavaScriptServices/issues/1258#issuecomment-327818748

14. 路由打包时构建错误,ModuleWithProviders未被成功引入

npm包会构建成这样:

打包前

export const routerModuleForChild = RouterModule.forChild(routers)

打包后

export declare const routerModuleForChild: import("@angular/core/src/metadata/ng_module").ModuleWithProviders<RouterModule>;;

正确写法:

import { ModuleWithProviders } from "@angular/core";

export const routing: ModuleWithProviders = RouterModule.forRoot(routers);

参考https://stackoverflow.com/questions/41134288/angular-2-routing-error-with-modulewithproviders

路由配置时报路由配置错误

unhandled Promise rejection: Invalid configuration of route 'pages/'. One of the following must be provided: component, redirectTo, children or loadChildren ; Zone: <root> ; Task: Promise.then ; Value: Error: Invalid configuration of route 'pages/'. One of the following must be provided: component, redirectTo, children or loadChildren

这是因为路由里面有个空的{}什么都没填,将其删除即可。

{ path: '401', component: Exception401Component, },
{
    // path: 'demo',
    // loadChildren: './demo/demo.module#DemoModule'
},
{ path: '403', component: Exception403Component},

删除后

{ path: '401', component: Exception401Component, },
{ path: '403', component: Exception403Component},

更多用法更新于 github