使用导入时,TypeScript无法解析模块 [英] TypeScript won't resolve module when import is used
问题描述
// Modules/MyModule.ts --------------------------------
import fs = require("fs");
module Hello {
export function World(): string {
return "Hello World";
}
}
// Main/App.ts ----------------------------------------
console.log(Hello.World()); // Cannot find name 'Hello'
由于某种原因,这会产生上面指定的错误.奇怪的是,如果我取消对import语句的注释,我将不再收到此错误. (反正不使用)
For some reason this produces the error specified above. The weird thing is if I uncomment the import statement I don't get this error anymore. (it's not used anyway)
两者都会产生相同的错误:
Both produce the same error:
tsc Main/App.ts --module "commonjs"
tsc Main/App.ts --module "amd"
这真的是一个编译器错误,还是我错过了一些东西.我是否需要指定外部模块要求有所不同?
Is this really a compiler bug or am I missing something. Do I need to specify external module requires somehow different?
推荐答案
这个问题很多-TypeScript中获得快乐和幸福的关键是选择 内部模块 外部模块,而不是同时使用这两个模块.
This one comes up quite a lot - the key to joy and happiness in TypeScript is to choose either internal modules or external modules and not both.
I have written more extensively about choosing between internal and external modules in TypeScript. The bottom line is choose only one.
在您的情况下,您需要完全提交给外部模块.这是一个更新的示例:
In your case, you need to fully commit to external modules. Here is an updated example:
// Modules/Hello.ts --------------------------------
import fs = require("fs");
export function World(): string {
return "Hello World"
}
上述文件的模块名称为Hello
,因为它位于名为Hello.ts
的文件中.
The module name for the above file is Hello
, because it is in a file named Hello.ts
.
然后您可以像这样使用它...
You can then use it like this...
// Main/App.ts ----------------------------------------
import Hello = require("./Modules/Hello");
console.log(Hello.World());
p.s.节点应用程序使用commonjs
模式进行编译-但这也适用于AMD.
p.s. Node apps are compiled using commonjs
mode - but this works for AMD too.
这篇关于使用导入时,TypeScript无法解析模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!