我在同一个文件夹中有两个文件:
/src/routes/file1.ts
/src/routes/file2.ts
file1.ts
function greet(name: srting){
return 'Hello +' name
}
export = greet;
file2.ts(引用file1 )
var f2 = require('./file1');
function another_greeting(name: string)
{
return f1.greet(name) + name;
}
exports f2;
此配置有效,没问题。但是如果在file2中我以这种方式指向file1
import f1 = require('./file1')
编译器抱怨错误:无法找到模块'。/ file1' 这提示我问:使用“import”语句和“var”语句导入外部文件有什么区别?
答案 0 :(得分:2)
基本区别在于,当您使用import
时,TypeScript编译器(TSC)检查是否可以通过TypeScript编译器配置找到文件./file1
(我的意思是主要是--module
flag)!如果仅使用var f2 = require('./file1');
,则TypeScript不会进行此类检查。
您可以从测试中看到TSC如何为import
模块和commonjs
模块转换关键字AMD
:
CommonJS: https://github.com/Microsoft/TypeScript/blob/master/tests/baselines/reference/commonjsSafeImport.js
tests/baselines/reference文件夹中有许多其他测试。
因此,在您的情况下,import
应转换为var
。
为什么它不起作用?好吧,以下工作在我的电脑上:
<强> 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'));
我像这样编译脚本:
c:\Work\TypeScript-playground>tsc --module commonjs --target es5 file2.ts
并按照以下方式运行:
c:\Work\TypeScript-playground>node file2.js
答案 1 :(得分:0)
我终于能够在chrome中调试我的.ts文件了,通过遵循这个建议How can I debug modular TypeScript with source maps?在.ts文件中正常点击mt断点,它运行得非常好。它伤心地看到,微软并没有为调试自己的技术,而谷歌能做到这一点提供了合适的工具。