Reputation: 5346
I have two files in the same folder:
/src/routes/file1.ts
/src/routes/file2.ts
file1.ts
function greet(name: srting){
return 'Hello +' name
}
export = greet;
file2.ts (references file1)
var f2 = require('./file1');
function another_greeting(name: string)
{
return f1.greet(name) + name;
}
exports f2;
This configuration works, no problem. But if in file2 I point to file1 this way
import f1 = require('./file1')
the compiler complaints with error: Cannot find module './file1' This prompts me to ask: what is the difference between importing an external file with the "import" statement and the "var" statement?
Upvotes: 3
Views: 1167
Reputation: 5346
I was finally able to debug my .ts file in chrome, hitting normally mt breakpoints inside .ts file by following this suggestion How can I debug modular TypeScript with source maps? and it is working really well. It sad to see that microsoft has not provided proper tool for debugging their own technology while google is able to do that.
Upvotes: 0
Reputation: 28648
The basic difference is that when you use import
then TypeScript compiler (TSC) checks if the file ./file1
can be found by based on TypeScript compiler configuration (I mean mainly --module
flag)! If you use only var f2 = require('./file1');
then TypeScript does no such checking.
You can see from tests how is the keyword import
transpiled by TSC for commonjs
modules and for AMD
modules:
CommonJS: https://github.com/Microsoft/TypeScript/blob/master/tests/baselines/reference/commonjsSafeImport.js
There are many other tests in tests/baselines/reference folder.
So in your case import
should be translated to var
.
And why does it not work? Well, the following works on my computer:
file1.ts:
function greet(name: string){
return 'Hello ' + name;
}
export = greet;
file2.ts:
import f1 = require('./file1');
function another_greeting(name: string)
{
return f1(name) + name;
}
console.log(another_greeting('test'));
I compile the scripts like this:
c:\Work\TypeScript-playground>tsc --module commonjs --target es5 file2.ts
and run like this:
c:\Work\TypeScript-playground>node file2.js
Upvotes: 2