Javascript typescript声明第三方模块

Javascript typescript声明第三方模块,javascript,typescript,declare,Javascript,Typescript,Declare,我如何声明第三方模块,该模块如下所示: declare module "foo-module" { function foo(): void; export = foo; } declare module "foo-module" { function foo(): void; namespace foo { } // This is a hack to allow ES6 wildcard imports export = foo; } import foo = r

我如何声明第三方模块,该模块如下所示:

declare module "foo-module" {
  function foo(): void; 
  export = foo;
}
declare module "foo-module" {
  function foo(): void; 
  namespace foo { } // This is a hack to allow ES6 wildcard imports
  export = foo;
}
import foo = require("foo-module");
foo();
在第三方模块中:

module.exports = function foo(){
  // do somthing
}
在我的代码中:

import * as foo from 'foo-module'; // Can not find a declaration module for ...
foo();

您声明该函数:

声明var foo:任何

这将告诉Typescript,在某个地方您有一个名为foo的函数,您将确保在站点上注入该函数。

请查看

如何编写声明在很大程度上取决于模块的编写方式及其导出内容

您给出的示例是CommonJS模块(
module.exports=…
),它实际上不是有效的ES6模块,因为ES6无法将函数导出为模块(它只能导出函数成员或默认函数)

TypeScript 2.7的更新+ 添加后,对于具有非ES6兼容导出的CommonJS模块,您不再需要使用下面所示的“名称空间攻击”

首先,确保在
tsconfig.json
中启用了
esModuleInterop
(现在默认情况下,它包含在
tsc--init
中):

.d.ts
文件中声明您的
foo示例
,如下所示:

declare module "foo-module" {
  function foo(): void; 
  export = foo;
}
declare module "foo-module" {
  function foo(): void; 
  namespace foo { } // This is a hack to allow ES6 wildcard imports
  export = foo;
}
import foo = require("foo-module");
foo();
现在,您可以将其导入为所需的名称空间:

import * as foo from "foo-module";
foo();
import * as foo from "foo-module";
foo();
或作为默认导入:

import foo from "foo-module";
foo();
旧的解决方法 您可以在
.d.ts
文件中声明
foo示例
,如下所示:

declare module "foo-module" {
  function foo(): void; 
  export = foo;
}
declare module "foo-module" {
  function foo(): void; 
  namespace foo { } // This is a hack to allow ES6 wildcard imports
  export = foo;
}
import foo = require("foo-module");
foo();
并按您的要求导入:

import * as foo from "foo-module";
foo();
import * as foo from "foo-module";
foo();
或者像这样:

declare module "foo-module" {
  function foo(): void; 
  export = foo;
}
declare module "foo-module" {
  function foo(): void; 
  namespace foo { } // This is a hack to allow ES6 wildcard imports
  export = foo;
}
import foo = require("foo-module");
foo();


我有一个类似的问题。并努力将类型定义添加到我的项目中。最后我想了想

这是一些模块(仅包含常量),让我们将其称为
some module
-node\u modules/some module/index.js

'use strict';

exports.__esModule = true;
var APPS = exports.APPS = {
    ona: 'ona',
    tacq: 'tacq',
    inetAcq: 'inetAcq'
};
首先,我添加到tsconfig.json
baseUrl
typeroot

{
  ...
  "compilerOptions": {
    ...
    "baseUrl": "types",
    "typeRoots": ["types"]
  }
  ...
}
第二,在我的项目根目录中,我为模块
types/some module/index.js创建文件夹
types
,使用相同的文件夹结构,并放置代码:

declare module 'some-module' {
    type Apps =  {
        ona: string;
        tacq: string;
        inetAcq: string;
    };
    let APPS: Apps
}
最后,我可以通过打字将它导入我的
my file.ts

import { APPS } from 'some-module';
如果模块内部已经调用了
foo()
,结果是导出的内容,会发生什么情况?你怎么打?