首页 > 解决方案 > 如何在导出函数和命名空间类型的角度应用程序中导入“npm”模块?

问题描述

我已经安装了 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 文件有关,因为它没有 option "typings": "index.d.ts"。但是我尝试添加此选项并没有得到任何结果。

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

我究竟做错了什么 ?

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

控制台有错误。

标签: angulartypescriptnode-modulestypescript-typingscommonjs

解决方案


我刚刚检查了库:

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}'

推荐阅读