【问题标题】:How to import `npm` module in angular application that exports function and namespace with types?如何在导出函数和命名空间类型的角度应用程序中导入“npm”模块?
【发布时间】:2019-09-14 18:05:32
【问题描述】:

我已经安装了npm包https://github.com/alferov/array-to-tree/

npm install array-to-tree --save

在它的 index.d.ts 文件中有函数和命名空间的声明:

export = arrayToTree;

declare function arrayToTree<T>(data: T[], options?: Partial<arrayToTree.Options>): Array<arrayToTree.Tree<T>>;

declare namespace arrayToTree {
    interface Options {
        childrenProperty: string;
        parentProperty: string;
        customID: string;
        rootID: string;
    }

    type Tree<T> = T & {
        children?: Array<Tree<T>>;
    };
}

我尝试以这种方式在我的 Angular 应用程序中导入它:

import * as arrayToTree from 'array-to-tree';

但是我得到了编译错误:

错误 TS2307:找不到模块“arrayToTree”。

我也尝试使用 CommonJS 样式导入:

import arrayToTree = require('array-to-tree');

代码编辑器出错:

TS1202:以 ECMAScript 模块为目标时无法使用导入分配。考虑改用'import * as ns from "mod"''import {a} from "mod"''import d from "mod"'

我尝试了所有建议的变体,但没有解决问题。

我认为这个问题可能与 npm-package 中的 package.json 文件有关,因为它没有选项 "typings": "index.d.ts"。但是我尝试添加此选项并没有得到任何结果。

我认为问题在于将命名空间与函数一起导入。 或者可能是兼容性 Typescript 版本和 index.d.ts 文件格式的问题?我使用 Typescript 3.2.2。

我做错了什么?

更新: 我在stackblitz上做例子: https://stackblitz.com/edit/angular-ehjdfy

控制台有错误。

【问题讨论】:

    标签: angular typescript node-modules typescript-typings commonjs


    【解决方案1】:

    我刚刚检查了库:

    import * as arrayToTree from 'array-to-tree' 工作正常。

    节点 ./node_modules/ts-node/dist/bin.js

    > import * as arrayToTree from 'array-to-tree'
    {}
    > arrayToTree.toString()
    'function arrayToTree(data, options) {\n  options = Object.assign(\n    {\n      parentProperty: \'parent_id\',\n      childrenProperty: \'children\',\n      customID: \'id\',\n      rootID: \'0\'\n    },\n    options\n  );\n\n  if (!Array.isArray(data)) {\n    throw new TypeError(\'Expected an array but got an invalid argument\');\n  }\n\n  var grouped = groupByParents(deepClone(data), options);\n  return createTree(\n    grouped,\n    grouped[options.rootID],\n    options.customID,\n    options.childrenProperty\n  );\n}'
    

    【讨论】:

    • 你用 javascript 测试它?我在 Typescript 的 Angular 应用程序中使用它。可能是角度或 ts-compiler 配置的问题?它找不到必要的文件?
    • 不,我在 TypeScript 中检查过,注意 node ./node_modules/ts-node/dist/bin.js 启动了 TypeScript 解释器。就像全局安装 ts-node npmjs.com/package/ts-node.
    • 是的,谢谢,我明白了。你用的是什么TS版本?如果它是最新版本之一,我认为问题出在 angular 或 ts 配置文件...
    • 您能选择一个答案吗?我建议您为您的新问题创建一个新帖子。
    • 问题是一样的 - 导入问题。我用stackblitz.com/edit/angular-ehjdfy 上的示例更新了帖子
    猜你喜欢
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2018-08-10
    • 2016-04-27
    • 2020-06-27
    • 1970-01-01
    • 2017-11-03
    • 2019-01-08
    相关资源
    最近更新 更多