typescript: what is the difference between import and var

advertisements

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?


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

AMD: https://github.com/Microsoft/TypeScript/blob/master/tests/baselines/reference/amdImportNotAsPrimaryExpression.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