【问题标题】:typescript declare third party modules打字稿声明第三方模块
【发布时间】:2017-10-18 21:05:23
【问题描述】:

我如何声明一个看起来像这样的第三方模块:

在第三方模块中:

module.exports = function foo(){
  // do somthing
}

在我的代码中:

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

【问题讨论】:

    标签: javascript typescript declare


    【解决方案1】:

    查看documentation on working with 3rd party modules

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

    您给出的示例是一个 CommonJS 模块 (module.exports = ...),它不是真正有效的 ES6 模块,因为 ES6 无法导出函数作为模块(它只能导出函数成员或 default 函数)。

    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

    【讨论】:

    • 如果foo() 已经在模块内部调用并且结果是导出的结果会怎样?你怎么打出来的?
    【解决方案2】:

    我遇到了类似的问题。并努力将类型定义添加到我的项目中。终于想到了。

    这是一些模块(只有常量),我们称之为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 baseUrltypeRoots

    {
      ...
      "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';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2021-12-06
      • 1970-01-01
      相关资源
      最近更新 更多