2016-07-29 25 views
0

這裏是.js文件:如何用javascript模塊插入打字稿文件

var mongoose=require('mongoose'); 
var express=require('express'); 
var app=express(); 

var connect=mongoose.connect("mongodb://localhost:27017/techo2log"); 
var schema=mongoose.Schema; 
var userschema=new schema(
{ 
    name:String, 
    age:Number, 
    address:String, 
    created_at:Date, 
    updated_at:Date, 

} 
); 

var User=mongoose.model('User',userschema); 
userschema.method.dudify=function() 
{ 
this.name=this.name+'-dude'; 
return this.name; 
} 

//making the model available to the external file 
module.exports=User; 

我想使用的用戶模塊中我喜歡的類型的腳本file.How我應該寫在上面的代碼打字稿定義文件這樣我可以導入我的.ts文件。

+0

的[如何導入一個js庫沒有打字稿文件定義文件]可能的複製(http://stackoverflow.com/問題/ 22842389/how-to-import-a-js-library-without-definition-file-in-typescript-file) –

回答

0

我假設你編寫了一個NodeJS模塊,所以首先確保你使用--module commonjs作爲編譯器選項(或者在你的tsconfig.json中)。

其次,您只需要創建一個定義文件。如果你的JS文件名爲「user.js的」,你能說出你的定義文件「user.d.ts」,可能是這樣的:

declare module 'user' { 
    var User: any; 
    export = User; 
} 

當然,你可以細化User類型,但作爲一個開始,這應該可以做到。

第三,你可以用這樣的行導入打字稿你的模塊:

import User = require('user'); 
+0

我得到的錯誤是「在打字稿中導入時無法找到模塊'user' –

+0

我有嘗試所有的東西,但仍然得到相同的錯誤。也嘗試添加///