javascript - 使用 node 导入 typescript
我刚开始前端网页开发(在这些包管理器/打包工具中,JavaScript简直是地狱),我正在尝试使用 TypeScript + Browserify
所以我创建了一个 index.ts 文件,并下载了 uniq 模块(使用 npm)只是为了测试 ts 文件的编译
这是我的 index.ts
/// <reference path="node_modules/uniq/uniq.d.ts" />
import {unique} from "uniq";
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
console.log(unique(data));
uniq.d.ts
// Type definitions for uniq
// Project: https://www.npmjs.com/package/uniq
// Definitions by: Hans Windhoff <https://github.com/hansrwindhoff>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Uniq{
<T>(ip:Array<T>): Array<T>;
}
declare var uniq :Uniq;
declare module "uniq" {
export = uniq;
}
目录结构
.
├── entry.ts
├── node_modules
│ └── uniq
│ ├── LICENSE
│ ├── package.json
│ ├── README.md
│ ├── test
│ │ └── test.js
│ ├── uniq.d.ts
│ └── uniq.ts
└── package.json
但是当我尝试编译 index.ts 时,我收到这个错误:
error TS2688: Cannot find type definition file for 'uniq'.
答案#1
第一
你可能路径错了:
/// <reference path="node_modules/uniq/uniq.d.ts" />
也许是 ../../node_modules/uniq/uniq.d.ts。请不要使用像这样的脆弱路径,而是使用 tsconfig.json :https://basarat.gitbooks.io/typescript/content/docs/project/tsconfig.html
第二
根据你展示的 .d.ts 文件,你的导入 import {unique} from "uniq"; 也是错误的。它应该是 import unique=require('uniq'),因为它是单函数导出。修复第一个问题后你无论如何都会遇到关于这个的错误。享受吧 🌹
