【问题标题】:How to include npm packages in angular cli如何在 Angular cli 中包含 npm 包
【发布时间】:2017-09-16 15:38:11
【问题描述】:

到目前为止,我从 angular-seed 练习了我的 Angular 2 项目 here

在做这个项目时,我习惯于像这样在 system.config.js 中包含所有第三方库

 map: {
   'ng2-file-upload': 'npm:ng2-file-upload'
 },
 packages: {
  ng2-file-upload: {
    defaultExtension: 'js'
  }

这对我来说效果很好。现在我正在使用 angular cli,但我对包含在其中感到困惑。

在 angular-cli.json 中,

 "scripts": [
     ?????
  ],

谁能帮帮我。谢谢

【问题讨论】:

  • AFAIR 你可以将你的脚本直接导入到你的组件中,然后不需要包含在你的angualr-cli.json 例如:import {DropdownModule} from 'primeng/components/dropdown/dropdown';

标签: angular angular2-routing


【解决方案1】:

您将依赖项存储在node_modules 文件夹中。当您需要它们时,您可以使用 import 语句将它们导入文件中。编译成 JS 时,import 通常会被替换为require

当您在浏览器中执行代码时,您需要一个加载器来从node_modules 加载这些文件,这样的加载器就是 SystemJS。了解更多为什么需要 SystemJS here。 SystemJS 需要知道模块的路径,这就是为什么你需要添加依赖到system.config.js

但是,angular-cli 使用 webpack 模块捆绑器,它有自己的内置加载器。当 webpack 打包文件时,它会解析路径并将它们内联到生成的包中。这就是为什么在使用angular-cli 时不需要在任何地方添加路径。

我刚刚尝试将ng2-tag-inputangular-cli 一起使用。一切正常。我刚刚将以下内容导入主模块:

...
import {TagInputModule} from 'ng2-tag-input';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
    TagInputModule, BrowserAnimationsModule
  ],

并安装了@angular/animations。以下 sn-p 工作正常:

@Component({
  template: '<tag-input [(ngModel)]='items'></tag-input>',
  ...
})
export class AppComponent {
  items = ['Pizza', 'Pasta', 'Parmesan'];
}

你还需要安装@angular/animations

【讨论】:

  • 这很有趣 Maximus,刚才我正在通过 module.ts 中的 npm 导入标签,就像这样 import { TagInputModule } from 'ng2-tag-input';
  • 但它不起作用。我应该从文件中导入还是只需要文件夹就足够了
  • @MMR,你能说得更具体点吗?什么是行不通的?你有 TS 编译错误吗?或运行时错误?还是 webpack 错误?
  • 我把它当作 eerors .......ng:///TagInputModule/TagInputComponent.ngfactory.js:369 错误类型错误:无法读取属性'get' undefined(…)View_TagInputComponent_0 @ ng:///TagInputModule/TagInputComponent.ngfactory.js:369 ng:///TagInputModule/TagInputComponent.ngfactory.js:369 错误
  • 你能设置一个plunker吗?我会尝试在本地重现
【解决方案2】:

我没有使用过 SystemJS,但是:

是的,您可以将您的库添加到scripts

"scripts": [
    "pathToLibray"
]

但是如果你有一个为 Angular 构建的 npm 包,你可以在不导入的情况下使用它。它会从您的 node_modules 自动加载

希望我能帮上忙:)

【讨论】:

  • 嗨 Raphael,因此,如果我也有 20 个 .js 文件,我不需要在 angular cli 中导入?直接在我的组件中导入它就可以工作吗?
  • 是的,应该的。
猜你喜欢
  • 1970-01-01
  • 2021-08-19
  • 2019-08-22
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
  • 1970-01-01
相关资源
最近更新 更多