相当于 Typescript 声明文件中的 module.exports

Tui*_*izi 6 typescript

我尝试做一个库的声明文件。

library.js文件中,有:

if (typeof module !== 'undefined' /* && !!module.exports*/) {
    module.exports = Library;
}
Run Code Online (Sandbox Code Playgroud)

我应该在我的library.d.ts文件中放入什么才能在我的代码中导入和使用这个库?

我希望能够做到:

import { Library } from 'library';
const instance = new Library();
Run Code Online (Sandbox Code Playgroud)

Cam*_*ind 6

正如@Nitzan 所指出的,您需要使用特殊export =import Library = require语法:

出口 = 和进口 = 要求()


一个完整的例子:

node_modules/library/index.js

module.exports = function(arg) {
  return 'Hello, ' + arg + '.';
}
Run Code Online (Sandbox Code Playgroud)

library.d.ts 这个文件名在技术上无关紧要,只有.d.ts扩展名。

declare module "library" {
  export = function(arg: string): string;
}
Run Code Online (Sandbox Code Playgroud)

source.ts

import Library = require('library');

Library('world') == 'Hello, world.';
Run Code Online (Sandbox Code Playgroud)

  • 我在“export = function ...”示例中收到“'{'预期”错误... (2认同)

Nit*_*mer 2

在以下情况下必须使用此语法export =

import Library = require("library");
Run Code Online (Sandbox Code Playgroud)

更多相关信息请参见:export = 和 import = require()