我在这里遗漏了 TypeScript 中一些简单的东西......
使用 Chrome 运行我的代码,我有一个工作的 typescript 环境,我的所有其他代码/模块都按预期工作。
当我从 .d.ts 导入时,所有内容都在编译时没有错误/警告,但我在 Chrome 中遇到运行时错误,因为生成的 JavaScript 试图从一个不存在的文件中导入。
import { doSomething } from "exampleJsLibrary";
在浏览器中失败,因为 TypeScript 没有将 exampleJsLibrary.d.ts 转换为 JS 文件。
我的目标是 es5,使用 es6 模块输出,并使用 tsc 构建(没有 webpack/browserify 工具),ts 2.7.2。
完整示例:
<!DOCTYPE html>
<html>
<head>
<script>
var exampleJsLibrary = (function() {
return {
doSomething: function(x) { return x + 1 }
}
})()
</script>
<script type="module" src="./built/myCode.js"></script>
</head>
<body>
</body>
</html>
和
// exampleJsLibrary.d.ts
export const doSomething(x: number): number;
export as namespace exampleJsLibrary;
// myCode.ts
import { doSomething } from "./exampleJsLibrary";
function test() {
console.log(doSomething(3));
}
// tsconfig.json
...
"target": "es5",
"lib": ["dom", "es5", "es2015.iterable", "es2015"],
"outDir": "built",
"module": "es6"
...
失败是因为myCode.js生成的代码
仍然有行 import { doSomething } from "./exampleJsLibrary"
,
这会导致运行时错误,因为没有 exampleJsLibrary 或 exampleJsLibrary.js。
如果我用 var doSomething = exampleJsLibrary.doSomething
替换生成的 JS 中的那一行,一切正常。
如何从 .d.ts 导入?
最佳答案
.d.ts
declaration files只包含类型声明,而不是实际代码。 (它们就像 C/C++ 中的头文件,如果您碰巧熟悉的话。)您需要在项目中包含实际的库代码,然后导入它或全局定义它以使其在运行时运行.
在您的情况下,由于库代码作为全局代码包含在页面中,因此您不需要使用import
。相反,你可以说:
const doSomething = exampleJsLibrary.doSomething
如果编译器提示 exampleJsLibrary
未定义,最简单的解决方法是将其添加到文件顶部(使用 .d.ts 的实际相对路径):
/// <reference path="path/to/exampleJsLibrary" />
(请注意,如果您的包是从 npm 包含的,则方法会有所不同,这很常见。)
关于typescript - 导入任何 .d.ts 都会导致运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49823106/