module.exports in typescript

后端 未结 4 1900
半阙折子戏
半阙折子戏 2020-12-13 03:30

does somebody know how to do a module.exports?

I tried some different ways ending up with

export class Greeter         


        
相关标签:
4条回答
  • 2020-12-13 03:42

    So I think I've found a workaround. Just wrap the keyword 'module' in parentheses in your .ts file:

    declare var module: any;
    (module).exports = MyClass;
    

    The generated javascript file will be exactly the same:

    (module).exports = MyClass;
    

    Note, better than declaring var module yourself, download the node.d.ts definition file and stick it in the same directory as your typescript file. Here is a complete sample of an express node.js routing file which assumes node.d.ts is in same directory:

    /// <reference path="node.d.ts" />
    var SheetController = function () {
        this.view = function (req, res) {
            res.render('view-sheet');
        };
    };
    (module).exports = SheetController;
    

    I can then new up a SheetController and (using express) assign the view method:

    var sheetController = new SheetController();
    app.get('/sheet/view', sheetController.view);
    

    I suppose any keyword can be escaped using this pattern:

    declare var reservedkeyword: any;
    (reservedkeyword).anything = something;
    
    0 讨论(0)
  • 2020-12-13 04:00

    It's ugly and hacky, but you can still do:

    class Greeter {}
    declare var exports:any;
    exports = Greeter;
    

    Which compiles into:

    var Greeter = (function () {
        function Greeter() { }
        return Greeter;
    })();
    exports = Greeter;
    
    0 讨论(0)
  • 2020-12-13 04:06

    You can export a single class in TypeScript like this:

    class Person {
    
      private firstName: string;
      private lastName: string;
    
      constructor(firstName: string, lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
    
      public getFullName() {
        return `${this.firstName} ${this.lastName}`;
      }
    }
    
    export = Person;
    

    And here is how it's going to be used:

    var Person = require('./dist/commonjs/Person.js');
    
    var homer = new Person('Homer', 'Simpson');
    var name = homer.getFullName();
    
    console.log(name); // Homer Simpson
    

    To be complete, here is my tsconfig.json (I am using TypeScript v2.0.3):

    {
      "compilerOptions": {
        "module": "commonjs",
        "moduleResolution": "node",
        "outDir": "dist/commonjs",
        "rootDir": "src/ts",
        "target": "es5"
      },
      "exclude": [
        "dist",
        "node_modules"
      ]
    }
    
    0 讨论(0)
  • 2020-12-13 04:06

    This has now been implemented and is ready in TypeScript 0.9 :)

    0 讨论(0)
提交回复
热议问题