2016-02-27 21 views
0

我想创建一个简单的Node.js控制台应用程序使用TypeScript ECMAScript6使用Visual Studio 2015社区版,并且不能够使用app.ts中模块内定义的类。 Visual Studio的但是不显示模块“DataModels”作为命名空间,也在智能感知类,但它抛出一个错误,而在app.ts初始化它如何在单独文件中的命名模块内使用类?抛出ReferenceError:模块没有定义

错误:的ReferenceError:DataModels没有定义

VS试过项目设置使用AMD和CommonJs作为模块系统,但没有运气。

文件夹结构

/ 
app.ts 
DataModels.ts 
Scripts 
    Typings (dir) 
    Node (dir) 
    node.d.ts 

app.ts

/// <reference path="DataModels.ts" /> 
var user: IUser = new DataModels.User(); 
user.Name = 'user1'; 
console.log(user.Name); 

DataModels.ts

interface IUser { 
    Name: string; 
    Email: string; 
    UserName: string; 
    Password: string; 
    ProfilePicPath: URL; 

} 

module DataModels { 

    export class User implements IUser { 
     private _name: string; 
     private _email: string; 
     private _username: string; 
     private _password: string; 
     private _profilePicPath: URL; 

     public get Name() { 
      return this._name; 
     } 
     public set Name(value) { 
      this._name = value; 
     } 

     public get Email() { 
      return this._email; 
     } 
     public set Email(value) { 
      this._email = value; 
     } 

     public get UserName() { 
      return this._username; 
     } 
     public set UserName(value) { 
      this._username = value; 
     } 

     public get Password() { 
      return this._password; 
     } 
     public set Password(value) { 
      this._password = value; 
     } 

     public get ProfilePicPath() { 
      return this._profilePicPath; 
     } 
     public set ProfilePicPath(value) { 
      this._profilePicPath = value; 
     } 
    } 
} 

回答

1

Tried VS project settings using AMD and CommonJs as module system but no luck.

您的代码将不会与任何模块系统工作,因为它不写在外部模块格式,它无线如果你将你的项目编译成单个文件,那么你只能工作。现在,假设你想使用某种这里的模块系统是你应该怎么写你的代码与AMD/CommonJS的等工作:

app.ts

// note the lack of reference paths 
import * as DataModels from './DataModels'; 

var user: DataModels.IUser = new DataModels.User(); 
user.Name = 'user1'; 
console.log(user.Name); 

DataModels.ts

export interface IUser { 
    ... 
} 

export class User implements IUser { 
    ... 
} 
+0

进口*了运行时错误”,CnsoleApp2 \ DataModels.js:1 (函数(出口需要,模块,__filename,__dirname){类用户{ 的SyntaxError :块范围声明(let,const,function,class)尚未移植到strict模式之外。突出显示关键字“class”。 –

+0

//不得使用模块名称导入为.. //替换为使用下面的新名称: import * as'ModuleDataModels from'./DataModels'; var user:ModuleDataModels.IUser = new ModuleDataModels.User(); user.Name ='user1'; console.log(user.Name); –

+1

把''use strict';'放在源文件的顶部,这是在TypeScript 1.8中自动完成的,所以我猜你是在旧版本中。 –