角度打字稿自定义名称空间

时间:2018-07-21 14:28:01

标签: angular typescript

我正在测试自定义名称空间,以使import更好:

所有组件都添加到文件夹app\components\

enter image description here

文件conponents.module.ts

...
import { DashboardComponent } from './dashboard/dashboard.component';

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule,
    ServicesModule
  ],
  declarations: [
    DashboardComponent,
    ...
  ],
  exports:[
    MessagesComponent
  ]
})
export class ComponentsModule { }

paths添加到了tsconfig.ts

"baseUrl": "./src",
"paths":{
          "@beewest/components/*" : ["app/components/*"]
        },
如果将路径修改为:

components.module.ts失败,并显示错误ERROR in src/app/components/components.module.ts(11,36): error TS2307: Cannot find module '@beewest/components'.

import { DashboardComponent } from '@beewest/components/dashboard/dashboard.component';

Visual Studio代码未显示任何错误,但是ng serve返回了error TS2307: Cannot find module '@beewest/components/dashboard/dashboard.component'

有没有建议?

1 个答案:

答案 0 :(得分:0)

好像paths是在重启ng serve之后更新的。

@beewest/...根据配置的app/...解析为paths

import { DashboardComponent } from '@beewest/components/dashboard/dashboard.component';

要删除.../dashboard/dashboard.component,打字稿的module resolution需要将文件index.ts添加到文件夹app/components中,并带有export行:

export {DashboardComponent} from './dashboard/dashboard.component';

Nicer导入行:

import { DashboardComponent } from '@beewest/components';