如何在使用类型导出函数和命名空间的角度应用程序中导入`npm`模块?

问题描述 投票:0回答:1

我已经安装了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>>;
    };
}

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

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个回答
0
投票

我刚检查了这个库:

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}'
© www.soinside.com 2019 - 2024. All rights reserved.