Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

import - module.exports in typescript

does somebody know how to do a module.exports?

I tried some different ways ending up with

export class Greeter {}

which will compile to

exports.Greeter = Greeter;

But what I really want is this:

exports = Greeter;

So that I can use it like this:

import { Greeter } from "greeter";

const greeter = new Greeter();

and not

import { Greeter } from "greeter";

const greeter = new Greeter.Greeter();

Is this possible with Typescript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"
  ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...