Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何导入在Typescript中使用module.exports=的CommonJS模块_Typescript_Ecmascript 6_Typescript1.7 - Fatal编程技术网

如何导入在Typescript中使用module.exports=的CommonJS模块

如何导入在Typescript中使用module.exports=的CommonJS模块,typescript,ecmascript-6,typescript1.7,Typescript,Ecmascript 6,Typescript1.7,下面的代码生成有效的工作ES5,但发出以下错误。我使用的是Typescript 1.7.5,我想我已经阅读了整个语言规范,我不知道为什么会产生这个错误 error TS2349: Cannot invoke an expression whose type lacks a call signature. a.js(带默认导出的ES5环境模块) a.d.ts b.ts b.js(生成ES5): module.exports在CommonJS模块中导出一个文本值,但是export defa

下面的代码生成有效的工作ES5,但发出以下错误。我使用的是Typescript 1.7.5,我想我已经阅读了整个语言规范,我不知道为什么会产生这个错误

error TS2349: Cannot invoke an expression whose type lacks a call signature.
a.js(带默认导出的ES5环境模块)

a.d.ts

b.ts

b.js(生成ES5):


module.exports
在CommonJS模块中导出一个文本值,但是
export default
表示您正在导出一个
default
属性,而JavaScript代码实际上并不是这样做的

在这种情况下,正确的导出语法只是
export=myfunc

declare module "test" {
    function myfunc(): string;
    export = myfunc;
}

这个错误在哪一行?test.ts的第2行。顺便说一句,您的帖子对所有三个文件都使用了基本名称“test”,这让人非常困惑。第三个文件导入“/test”并称为“test.ts”,实际上肯定是其他文件。:)@CSnover我同意不清楚,所以我将文件名编辑为
a
b
a
是一个ES5 commonjs模块,没有预先存在的类型声明文件
b
是typescript消费的
a
。此外,
b.ts
中的
require()
也从
“/test”
更改为
“test”
,因为它应该是外部环境模块的字符串文字。我很惊讶它可以使用
“/test”
作为
test.js
的相对路径,但它确实有效。但这更好,因为这是Typescript规范中推荐的有效方法。非常感谢。我想打字稿规范真的把我引入歧途了。关于导出分配,它说,“导出分配的存在是为了与早期版本的TypeScript向后兼容。”(),这意味着这是旧方法,不应该在新代码中使用导出分配。另外,对于未来的读者来说,ES5中的
module.exports=
不是“默认导出”,而是ES6术语。Typescript规范解释了
默认
实体。要执行此操作,需要TS编译器选项中的
“esModuleInterop”:true
。还是我做错了什么?
declare module "test" {
    export default function (): string;
}
import test = require("test");
const app = test();
var test = require("test");
var app = test()
declare module "test" {
    function myfunc(): string;
    export = myfunc;
}