我已经阅读了有关如何将(流行的).js 库及其 d.ts 文件添加到 Typescript 模块文件的其他帖子和教程,但我陷入了错误消息的恶性循环。我对 Typescript 比较陌生,所以如果我的设置存在根本性问题,请告诉我。
我正在创建一个使用(以及其他)vis.js 数据集或 moment.js 函数的 .ts 模块。
VS Code 任务将我的 .ts 模块文件编译为 .js。当然,我想对正在使用的 js 库使用 IntelliSense。
vis.js 的 .d.ts 文件取自 DefinitiveTyped 项目。
文件结构:
/projectdir
/.vscode
tasks.json
/lib
vis.js
moment.js
/src
myModule.ts
-> myModule.js
-> myModule.js.map
/types
/vis/index.d.ts...
/jquery/index.d.ts...
index.html
tsconfig.json
tsconfig.json 的内容:
{
"compilerOptions": {
"module": "system",
"moduleResolution": "classic",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"target": "es5",
"sourceMap": true,
"watch": true,
"rootDir": "src",
"lib": ["es2015", "dom", "dom.iterable"],
"baseUrl": "types",
"typeRoots": ["types"]
},
"exclude": [
"./lib",
"**/*.js",
"**/*.js.map"
],
"include": [
"src/**/*.ts"
]
}
我的 VSCode tasks.json 的内容:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"command": "tsc",
"problemMatcher": "$tsc",
"tasks": [{
"type": "typescript",
"tsconfig": "tsconfig.json",
"group": {
"kind": "build",
"isDefault": true
}
}]
}
最后这是 myModule.ts:
export module datacore {
export var myDataSet = new vis.DataSet([]);
}
我在 tsconfig.json 中为 vis 和其他 js 库设置并引用了 .d.ts 文件。基本上它可以工作,但我收到了这个错误:
src/datacore.ts(2,33): error TS2686: 'vis' refers to a UMD global, but the current file is a module. Consider adding an import instead.
所以我考虑在我的模块之上添加一个导入:
import * as vis from "../lib/vis";
//also tried: import vis = require("../lib/vis");
export module datacore {
export var myDataSet = new vis.DataSet([]);
}
当我现在在 myModule.ts 文件上启动编译任务时,它需要很长时间,因为他显然也尝试编译 vis.js。一段时间后,我收到此错误:
Cannot write file '/Users/username/Desktop/timecore/lib/vis.js' because it would overwrite input file.
好吧,他不会写 vis.js,但我还是不想这样。为了防止他编译 .js 文件,我在 tsconfig.json 中将 "allowJs": 设置为 false。
现在编译速度要快得多,但会导致此错误:
src/datacore.ts(3,22): error TS6143: Module '../lib/vis' was resolved to '/Users/username/Desktop/timecore/lib/vis.js', but '--allowJs' is not set.
这是恶性循环关闭的地方。
我的设置有什么问题?
为了将 js 库正确导入我的 Typescript 模块,我需要做什么(这样我也可以使用 IntelliSense 在 VS Code 中进行类型检查)?