How do you write a node module using typescript?

后端 未结 2 932
遥遥无期
遥遥无期 2020-12-16 17:41

So, the general answer for the other question (How do you import a module using typescript) is:

1) Create a blah.d.ts definition file.

2) Use:

相关标签:
2条回答
  • 2020-12-16 18:08

    For JavaScript :

    var base = require('./base');
    var thing = require('./thing');
    module.exports = {
      Base: base.Base,
      Thing: thing.Thing
    };
    

    TypeScript :

    import base = require('./base');
    import thing = require('./thing');
    var toExport = {
      Base: base.Base,
      Thing: thing.Thing
    };
    export = toExport;
    

    Or even this typescript:

    import base = require('./base');
    import thing = require('./thing');
    export var Base = base.Base;
    export var Thing = thing.Thin;
    
    0 讨论(0)
  • 2020-12-16 18:08

    Typescript has really improved since this question was asked. In recent versions of Typescript, the language has become a much more strict superset of Javascript.

    The right way to import/export modules is now the new ES6 Module syntax:

    myLib.ts

    export function myFunc() {
      return 'test'
    }
    

    package.json

    {
      "name": "myLib",
      "main": "myLib.js",
      "typings": "myLib.d.ts"
    }
    

    Dependents can then import your module using the new ES6 syntax:

    dependent.ts

    import { myFunc } from 'myLib'
    
    console.log(myFunc())
    // => 'test'
    

    For a full example of a node module written in Typescript, please check out this boilerplate:

    https://github.com/bitjson/typescript-starter/

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