【问题标题】:How to import module in Angular?如何在 Angular 中导入模块?
【发布时间】:2017-06-20 09:30:35
【问题描述】:

我有一个 Angular 应用程序,我还创建了一个模块作为 npm 包。这是结构:

--otherModule
  --other-module.module.ts
  --index.ts
  --package.json

index.ts:

export { OtherModule } from './other-module.module';

other-module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';;

@NgModule({
  declarations: [ OtherComponent ],
  imports: [
    CommonModule
  ],
})
export class OtherModule {
} 

运行 npm link 后,我尝试在我的 AppModule 中使用这个模块,如下所示:

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { OtherModule } from 'other-module';

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

然后我收到以下错误:

模块“AppModule”导入的非预期值“OtherModule”。 请添加@NgModule 注解。

装饰器似乎不起作用或其他什么。有任何想法吗?

【问题讨论】:

  • 你能提供 other-module.module.ts 吗?
  • 是的,我更新了答案

标签: javascript angular npm


【解决方案1】:

import { OtherModule } from 'other-module.module'; 可以工作,您错过了为目录结构提供的模块扩展。

【讨论】:

  • 这不是问题
【解决方案2】:

我遇到了同样的问题,从父应用中删除 otherModule 的 node_modules 和 npm-installing 后解决了。

但是,必须不断地安装和卸载库的 node_modules(构建、测试和 IDE 了解依赖项中的类型都需要安装),这使得开发非常麻烦。

【讨论】:

    【解决方案3】:

    我遇到了这样的问题,我通过删除链接文件夹中的 node_modules 文件夹表单来修复它。

    对你来说,修复应该是从--otherModule 文件夹中删除 node_modules。这样,npm 就不会在里面搜索了。

    不知道是不是和你一样的问题,值得一试。

    【讨论】:

    • 但是你的 IDE 出现错误,因为他不知道这些库,不是吗?
    • 您应该 1 - 从链接的应用程序中删除 node_modules,2 - npm install 以安装链接的应用程序及其依赖项。这样,链接的应用程序将只有它使用的 pkgs,而 angular pkgs 将放置在根 node_modules 中。这样,您将拥有所有引用,但避免在两个 node_modules 文件夹(应用程序和链接的应用程序)中有角度 pkg。
    【解决方案4】:

    您的代码看起来不错,我已经在我的机器上模拟并运行了它。唯一的区别是您应该将文件从other-module.module.ts 更改为other.module.ts 或将您的模块名称从OtherModule 更改为OtherModuleModule,然后更新这些引用。

    我建议您使用命令ng g c other to component 和ng g m other to module 命令通过angular cli 创建组件和模块,以保持项目的标准。

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 2020-09-29
      • 2019-06-09
      • 2017-02-22
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多