使用模块的Typescript

我正在尝试构build我的第一个简单的基于ORM的Node JS应用程序。

我创build了这样的Database模块

 import * as Knex from 'knex'; import * as Bookshelf from 'bookshelf'; module Database { class Config { private static _knex: Knex = Knex({ client: 'mysql', connection: { host: '127.0.0.1', user: 'root', password: '', database: 'test', charset: 'utf8' } }); static _bookshelf: Bookshelf = Bookshelf(Config._knex); } export function bookshelf() { Config._bookshelf.plugin('registry'); Config._bookshelf.plugin(['virtuals']); return Config._bookshelf; } } 

我正在尝试在DAO类中使用它

 /// <reference path="../models/usermodel.ts" /> /// <reference path="../network/database.ts" /> module DAO { export class UserDAO { create(user: Model.User): Model.User { //Model.User is imported nicely var test = Database.bookshelf(); //what's wrong with this return null; } } } 

这是结束了这个错误dao/userdao.ts(18,24): error TS2304: Cannot find name 'Database'.

这是我第一次学习Typescript and Modules ,让我知道如果我做错了什么。

更新:只要我import statements in database.ts添加import statements in database.ts ,它不工作/找不到名称。 我正在做的错误通过使用import * as something from some

 // database.ts /// <reference path="<pathToKnexDefinetelyTypedFile>" /> // if you don't already have knex.d.ts // https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/knex/knex.d.ts /// <reference path="<pathToBookshelfDefinetelyTypedFile>" /> // if you don't already have bookshelf.d.ts // https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/bookshelf/bookshelf.d.ts // normally these references are unnecessary, but you have // to download all the ts for third libraries // you normally place them in a 'typings' folder // or choose another name for the folder, irrelevant, // then the IDE should recognize them (ts files) easily. import * as Knex from 'knex'; import * as Bookshelf from 'bookshelf'; module Database { class Config { private static _knex: Knex = Knex({ client: 'mysql', connection: { host: '127.0.0.1', user: 'root', password: '', database: 'test', charset: 'utf8' } }); static _bookshelf: Bookshelf = Bookshelf(Config._knex); } export function bookshelf() { Config._bookshelf.plugin('registry'); Config._bookshelf.plugin(['virtuals']); return Config._bookshelf; } } // Don't forget the export, that why you are getting that error export { Database } // dao.ts /// <reference path="../models/usermodel.ts" /> /// <reference path="../network/database.ts" /> import { Database } from './database'; module DAO { export class UserDAO { create(user: Model.User): Model.User { //Model.User is imported nicely var test = Database.bookshelf(); // what's wrong with this ? // Maybe the export and the import you forgot to add return null; } } } 

引用注释仅用于打字稿,它们不会被转录,您不会在生成的js中看到它们。 如果您的IDE能够识别项目中的所有ts文件,则引用注释是不必要的。

您必须导入/导出您在当前文件中使用的命名空间/模块,这是因为导入/导出被转换,它们将被编译为js,您将在生成的js中看到它们