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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:05:14  来源:igfitidea点击:

TypeScript cannot find js module in same folder

node.jstypescript

提问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 foovia relative path rather than looking for it in the node_modulesdirectory 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 .jsextension 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');

回答by Max Brodin

Try to use require without relative path

尝试在没有相对路径的情况下使用 require

var foo = require('foo');

See related articlefor details.

详情请参阅相关文章