TypeScript 在同一文件夹中找不到 js 模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32446039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript cannot find js module in same folder
提问by Emmett
I am struggling to load a .js module which is in the same folder as my .ts file. I have 4 file in the same folder:
我正在努力加载与我的 .ts 文件位于同一文件夹中的 .js 模块。我在同一个文件夹中有 4 个文件:
index.ts
索引.ts
/// <reference path="./node.d.ts" />
/// <reference path="./foo.d.ts" />
import foo = require('./foo.js');
node.d.ts
节点.d.ts
Copied from https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node.d.ts
复制自https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node.d.ts
foo.d.ts
食物.d.ts
declare module "foo" {
export function hello(): void;
}
foo.js
foo.js
module.exports = {
hello: function() {
console.log('hello');
}
};
When I run tsc index.ts --module commonjs
, I get the following error:
当我运行时tsc index.ts --module commonjs
,出现以下错误:
index.ts(4,22): error TS2307: Cannot find module './foo.js'.
采纳答案by curpa
Since node.js will resolve foo
via relative path rather than looking for it in the node_modules
directory like it would with a module you'd installed via npm, you need to drop declare module "foo"
in foo.d.ts
. Also, in index.ts
, drop the .js
extension when calling require
.
由于 node.js 将foo
通过相对路径解析,而不是node_modules
像使用通过 npm 安装的模块那样在目录中查找它,因此您需要declare module "foo"
放入foo.d.ts
. 此外,在index.ts
中,删除.js
时调用扩展require
。
foo.d.ts
食物.d.ts
export function hello(): void;
index.ts
索引.ts
/// <reference path="./node.d.ts" />
/// <reference path="./foo.d.ts" />
import foo = require('./foo');