【问题标题】:use npm package in Angular 2 component在 Angular 2 组件中使用 npm 包
【发布时间】:2018-02-15 14:44:29
【问题描述】:

我想在我的 Angular 4 组件中使用一个可用的 npm 包,但我很难让它工作。该软件包称为“ip”,可从https://www.npmjs.com/package/ip获得

我添加的包如下:

npm install ip --save

npm install --save @types/ip

在我的 app.module.ts 中有:

import { isV4Format } from 'ip';

我将 isV4Format 添加到 app.module.ts 的导入列表中

然后我尝试在我的班级中使用ip包如下:

import { isV4Format } from 'ip';

export class TabValidator {
    private static _check(address: string): any {
        const ip = require('ip');
        if (!myip.isV4Format(address)) { return { 'wrongFormat': true }; }
        return null;
    }
}

编译器抱怨组件:

找不到名称“需要”

关于 app.module.ts:

类型 '{ 声明的参数:(typeof InterfacesComponent | typeof EditnicComponent | typeof AppComponent)[]; i...' 不能分配给“NgModule”类型的参数。

有人能告诉我上面有什么问题吗?我怀疑有几件事不对劲。我在 SO 上发现了 2 个类似的问题,但它们似乎适用于不同的角度版本。

【问题讨论】:

  • 我按照其他地方的建议尝试了“npm install @types/node”,但没有帮助
  • 尝试将 require 块移动到导入的正下方,如下所示:import ... const ip = require('ip'); 然后在函数中使用它。如果没有帮助,则在 require 块中写入 js 的路径,例如 const Highcharts = require('highcharts/highstock');

标签: angular npm package


【解决方案1】:

关于 SO 有很多错误/过时的答案,包括这些错误的答案:

Cannot find name 'require' after upgrading to Angular4

Types not found

Angular 4: "Cannot find name 'require'

Angular 似乎让它变得更容易了;只需将其添加到您要使用节点模块的组件中:

export declare let require: any;
const ip = require('ip');

现在这可能不是实现您想要的最佳方式,因为我读过一些关于在 Angular 中使用“require”会对代码共享或类似内容产生负面影响的内容。但是,如果有人可以发布更好的答案,我会接受!

【讨论】:

    猜你喜欢
    • 2017-05-16
    • 2018-02-26
    • 2017-06-26
    • 1970-01-01
    • 2018-10-12
    • 2016-09-22
    • 2018-07-13
    • 2017-08-01
    • 1970-01-01
    相关资源
    最近更新 更多