使用TypeScript创建NodeJS模块

时间:2015-11-08 13:16:07

标签: javascript node.js typescript commonjs

我试图用TypeScript编写Node模块,这是我得到了多远:

MysqlMapper.ts

export class MysqlMapper{

    private _config: Mysql.IConnectionConfig;

    private openConnection(): Mysql.IConnection{
        ...
    }

    private createSelectAllQuery(constructor): string{
    ...
    }

    public getAll<T>(constructor): Q.Promise<Array<T>>{
    .....
    }
    constructor(config: Mysql.IConnectionConfig){
    ... 
    }

}

index.ts

export * from "./MysqlMapper";

的package.json

{
  "name": "mysql-metadata-orm",
  "version": "1.0.0",
  "description": "A Simple ORM using reflect-metadata",
  "main": "build/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "..."
  },
  "author": "+",
  "license": "MIT",
  "dependencies": {
    "mysql": "^2.9.0",
    "q": "^1.4.1",
    "reflect-metadata": "^0.1.2"
  }
}

我在tsconfig文件中激活了声明生成,但我真的不明白如何获取允许导入模块的声明文件:

import * as Mapper from "mysql-metadata-mapper"

我希望有人可以帮助我,因为它让我非常疯狂。

@Update

这些是生成的.d.ts文件:

index.d.ts

export * from "./MysqlMapper";

MysqlMapper.d.ts

import * as Q from "q";
import * as Mysql from "mysql";
export declare class MysqlMapper {
    private _config;
    private openConnection();
    private createSelectAllQuery(constructor);
    getAll<T>(constructor: any): Q.Promise<Array<T>>;
    constructor(config: Mysql.IConnectionConfig);
}

如何获取声明文件?

1 个答案:

答案 0 :(得分:0)

我建议您制作自己的声明文件:(例如globals.d.ts

declare module 'mysql-metadata-mapper' {
    import * as mapper from './MysqlMapper';
    export = mapper;
}

然后你可以参考这个声明文件,例如 /// <reference path="../globals.d.ts" />

并按照您的意愿导入模块:

import * as Mapper from 'mysql-metadata-mapper'

我不能100%确定这是否是最干净的解决方案,但至少它应该像你想要的那样工作。