Issue
I wrote the following files:
main.ts:
///<reference path="./external.ts"/>
hello();
external.ts
var hello = function() {
console.log("hello");
}
I compiled both files to javascript and ran them by the command: $ node main.js
I expected that function 'hello' will be invoked. But, no, I got an error:
ReferenceError: hello is not defined
The tutorial about triple-slash directive (https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html) says that:
The compiler performs a preprocessing pass on input files to resolve all triple-slash reference directives. During this process, additional files are added to the compilation.
so I don't understand why function from external.ts file cannot be read.
Solution
That aproach only works in the browser. When using node you need to import (require) the file in order to use it.
You'll need to do this:
// external.ts
export var hello = function() {
console.log("hello");
}
And use it like this:
// main.ts
import { hello } from "./external";
hello();
Also, when compiling you'll need to compile it for node:
tsc -m commonjs ./main.ts
Answered By - Nitzan Tomer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.