我正在努力加载.js模块,该模块与我的.ts文件位于同一文件夹中 . 我在同一个文件夹中有4个文件:
index.ts
/// <reference path="./node.d.ts" />
/// <reference path="./foo.d.ts" />
import foo = require('./foo.js');
node.d.ts
复制自https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node.d.ts
foo.d.ts
declare module "foo" {
export function hello(): void;
}
foo.js
module.exports = {
hello: function() {
console.log('hello');
}
};
当我运行 tsc index.ts --module commonjs
时,我收到以下错误:
index.ts(4,22): error TS2307: Cannot find module './foo.js'.
2 回答
尝试使用不带相对路径的require
有关详细信息,请参阅相关article .
由于node.js将通过相对路径解析
foo
而不是在node_modules
目录中查找它,就像你通过npm安装的模块那样,你需要在foo.d.ts
中删除declare module "foo"
. 此外,在index.ts
中,在调用require
时删除.js
扩展名 .foo.d.ts
index.ts