代码之家  ›  专栏  ›  技术社区  ›  tkruse

如何模块.导出函数和其他符号

  •  0
  • tkruse  · 技术社区  · 6 年前

    我想创建一个 newman plugin

    // in package newman-reporter-custom/index.ts
    module.exports = function(newmanEventEmitter: any, reporterOptions: any, collectionRunOptions: any) {
        ...
    };
    

    我的脑子里也有这个包.json: "main": "lib/index.js", "outDir": "lib",

    我还想导出一些其他类以使用与库相同的包。

    // in package newman-reporter-custom/index.ts
    import { foo } from "./foo";
    export { foo };
    

    // other npm package index.ts
    import { foo } from "newman-reporter-custom";
    

    module.exports = function(...), export { foo }; .

    如果我单独尝试两者中的任何一种,事情似乎都会很顺利。

    如果我尝试两者都做(以各种方式),要么newman不能加载我的包,比如 TypeError: Reporter is not a constructor TypeError: Class extends value undefined is not a function or null .

    在我看来模块.exports可以是函数(构造函数)或符号集合,但不能同时是两者。

    那么,满足newman和提供函数导出,以及导出其他符号的干净工作方式是什么呢?我可以灵活地从一个包裹到另一个包裹。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Fenton    6 年前

    TypeScript可以将标准ECMAScript模块语法转换成您喜欢的任何样式,因此下面是一个TypeScript模块的示例,该模块导出导入的成员:

    import { example } from './module';
    
    // Export a function
    export function foo() {
        return 2;
    }
    
    // Export an imported member
    export { example };
    

    调用代码只知道示例模块:

    import { foo, example } from './example';
    
        2
  •  0
  •   tkruse    6 年前

    使用单独API模块的解决方案

    我尝试了一个不同的模块,比如src/公共.ts哪个有

    // in package newman-reporter-custom/public.ts
    import { foo } from "./foo";
    export { foo };
    

    // other npm package index.ts
    import { foo } from "newman-reporter-custom/dist/public";
    

    /dist 部分。(这里似乎有讨论 https://github.com/nodejs/node/issues/14970