module.exports in typescript

后端 未结 4 1913
半阙折子戏
半阙折子戏 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 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"
      ]
    }
    

提交回复
热议问题