Typescript ///<reference path="...">:为什么它对我不起作用?

Cra*_*hax 5 typescript

我写了以下文件:

主要.ts:

///<reference path="./external.ts"/>

hello();
Run Code Online (Sandbox Code Playgroud)

外部.ts

var hello = function() {
    console.log("hello");
}
Run Code Online (Sandbox Code Playgroud)

我将这两个文件编译为 javascript 并通过以下命令运行它们: $ node main.js

我预计函数“hello”将被调用。但是,不,我收到一个错误:

ReferenceError:hello 未定义

关于三斜杠指令的教程(https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)说:

编译器对输入文件执行预处理过程以解析所有三斜杠引用指令。在此过程中,会将其他文件添加到编译中。

所以我不明白为什么无法读取 external.ts 文件中的函数。

Nit*_*mer 4

该方法仅适用于浏览器。使用节点时,您需要导入(需要)文件才能使用它。

你需要这样做:

// external.ts
export var hello = function() {
    console.log("hello");
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

// main.ts

import { hello } from "./external";

hello();
Run Code Online (Sandbox Code Playgroud)

另外,编译时您需要为节点编译它:

tsc -m commonjs ./main.ts
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,它在浏览器中不起作用。你知道如何在浏览器中实现它吗? (4认同)
  • 然后我收到错误:“Uncaught ReferenceError:未定义导出” (2认同)