【问题标题】:How to write a definition file for commonjs module that exports function如何为导出函数的commonjs模块编写定义文件
【发布时间】:2017-06-13 00:09:22
【问题描述】:

我想在 typescript 中使用简单的 commonjs 模块,这里有 3 个文件

原始库:

//commonjs-export-function.js
module.exports = function() {
    return 'func';
};

定义文件:

//commonjs-export-function.d.ts
declare function func(): string;
export = func;

使用它的打字稿程序:

//main.ts
import { func } from './commonjs-function';

console.log(func());

当我运行 tsc 时出现此错误:

tsc main.ts && node main.js
main.ts(1,22): error TS2497: Module '"/Users/aleksandar/projects/typescript-playground/commonjs-function"' resolves to a non-module entity and cannot be imported using this construct.

这里也已经回答了问题,但它不适用于 typescript 2.0

How to write a typescript definition file for a node module that exports a function?

【问题讨论】:

    标签: typescript commonjs typescript-typings typescript2.0


    【解决方案1】:

    供 CommonJS 使用 module.exorts = variable_name

    供 es2015 使用 导出默认 const/let 变量名 要么 变量定义

    导出默认变量名

    【讨论】:

      【解决方案2】:

      我最近在查找与 TypeScript 2.8.x 兼容的 CommonJS 模块定义示例时遇到了麻烦。这里尝试使用map-promise-limit 来演示该方法,这是一个带有a single CommonJS export 的包:

      declare module 'promise-map-limit' {
      
        type IIteratee<T, R> = (value: T) => Promise<R> | R;
      
        function mapLimit<T, R>(
          iterable: Iterable<T>,
          concurrency: number,
          iteratee: IIteratee<T, R>
        ): Promise<R[]>;
      
        export = mapLimit;
      
      }
      

      总而言之,使用单一函数类型导出为 CommonJS 模块创建类型定义:

      • 使用与任何其他ambient module 相同的declare module 语法
      • 在模块主体中声明一个命名函数(不使用declare关键字)
      • export =而不是export default导出函数

      [编辑] 意识到这类似于basarat's answer here。很划算!

      【讨论】:

        【解决方案3】:

        我在 typescript 文档中找到了解决方案:http://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-function-d-ts.html

        *~ Note that ES6 modules cannot directly export callable functions.
        *~ This file should be imported using the CommonJS-style:
        *~   import x = require('someLibrary');
        ...
        export = MyFunction;
        declare function MyFunction(): string;
        

        所以mu定义文件应该是:

        //commonjs-export-function.d.ts
        declare function func(): string;
        export = func;
        

        并使用 require 导入:

        //main.ts
        import func = require('./commonjs-export-function');
        

        【讨论】:

        • 哇,终于找到解决方案了,这可以节省我的时间,谢谢!
        猜你喜欢
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        • 2016-03-12
        • 1970-01-01
        • 1970-01-01
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多