angular - 如何在导出函数和命名空间类型的角度应用程序中导入“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
控制台有错误。
解决方案
我刚刚检查了库:
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}'
推荐阅读
- jquery - 为什么这个函数不会将页面加载到 div 中?(jQuery AJAX)
- c# - Visual Studio 2019 中的 SQL Server 数据库
- c++ - 如何在 vs 代码“C++”中安装和运行 boost 库
- c++ - U 没有命名类型 - 模板编译错误
- python-3.x - 更改时间列的数据类型-Pandas
- r - “上面列出了初始化中遇到的错误”(R)
- javascript - react-js中如何从组件中取出props数据?
- python - Scipy 和 Sklearn Yeo-Johnson 归一化结果不匹配
- python - 如何在所有列中找到一个值并将其放入新列中?
- ibm-mq - JMSWMQ2013:为队列管理器“QM1”提供的安全认证无效