我如何声明一个第三方模块,如下所示:
在第三方模块中:
module.exports = function foo(){
// do somthing
}在我的代码中:
import * as foo from 'foo-module'; // Can not find a declaration module for ...
foo();发布于 2017-05-19 09:37:50
查看documentation on working with 3rd party modules。
如何编写声明在很大程度上取决于模块是如何编写的以及它导出的内容。
您给出的示例是一个CommonJS模块(module.exports = ...),它实际上不是一个有效的ES6模块,因为ES6不能将函数导出为模块(它只能导出函数成员或默认函数)。
TypeScript 2.7+更新
有了添加的esModuleInterop compiler option,对于具有非ES6兼容导出的CommonJS模块,您不再需要使用下面所示的“名称空间黑客”。
首先,确保您已经在tsconfig.json中启用了esModuleInterop (现在默认包含在tsc --init中):
{
"compilerOptions" {
...
"esModuleInterop": true,
...
}
}在.d.ts文件中声明foo-example,如下所示:
declare module "foo-module" {
function foo(): void;
export = foo;
}现在,您可以将其作为您想要的名称空间导入:
import * as foo from "foo-module";
foo();或作为默认导入:
import foo from "foo-module";
foo();较旧的解决方法
您可以在.d.ts文件中声明foo-example,如下所示:
declare module "foo-module" {
function foo(): void;
namespace foo { } // This is a hack to allow ES6 wildcard imports
export = foo;
}并按您所需的方式导入:
import * as foo from "foo-module";
foo();或者像这样:
import foo = require("foo-module");
foo();documentation has a good resource on declaration files和一些templates for various kinds of declaration files
发布于 2019-02-15 20:28:10
我也遇到过类似的问题。并努力将类型定义添加到我的项目中。最后我想了想。
这是一些模块(只是带有常量),让我们称它为some-module -node_modules/ some module /index.js。
'use strict';
exports.__esModule = true;
var APPS = exports.APPS = {
ona: 'ona',
tacq: 'tacq',
inetAcq: 'inetAcq'
};首先,我添加了tsconfig.json baseUrl和typeRoots
{
...
"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';发布于 2017-05-19 06:06:24
您可以声明该函数:
声明var foo: any;
这将告诉Typescript,在某个地方有一个名为foo的函数,您将确保在站点上注入该函数。
https://stackoverflow.com/questions/44058101
复制相似问题