2012-03-30 34 views
2

我想知道是否可以從另一個coffeescript中需要一個coffeescript。從文件「user.coffee」從nodejs的另一個CoffeeScript文件中請求CoffeeScript文件

class UserObj 
    constructor: (@name) -> 
     console.log @name 

我的示例代碼

我的示例代碼從主文件

require "./user.coffee" 

User = new UserObj "Example" 

這是可能從CoffeeScript的文件或只是一個js文件中?

+0

[require()'從JavaScript文件或REPL提取CoffeeScript文件]的可能重複(http://stackoverflow.com/questions/4768748/requireing-a -coffeescript-file-from-a-javascript-file-or-repl) – 2012-03-30 13:00:18

回答

8

是的,它是可能的。

user.coffee:

exports.UserObj = 
class UserObj 
    constructor: (@name) -> 
     console.log @name 

main.coffee:

{UserObj} = require "./user" 

User = new UserObj "Example" 
+0

但是這只是針對Node而已?我認爲CoffeeScript可能會在編譯main.js – 2013-01-07 10:21:20

+0

@ThomasWelton時將所需的文件放在一起。這僅僅適用於Node。目前CoffeeScript編譯器只是一個文件到文件的編譯器,它不做任何項目結構分析,也沒有進行任何聚合。可能有[其他工具](https://github.com/jashkenas/coffee-script/wiki/Build-tools)來解決這個問題。我甚至記得[自己寫一個](https://github.com/nikita-volkov/Robusta)。 – 2013-01-07 10:38:18

+0

謝謝。後來我繼續使用requirejs,對於加載coffeescript模塊和類非常滿意。 – 2013-01-15 12:41:25

0

你可以使用這個庫coffee-stir包括其他依賴。這是一種解決方法,只能使用Web上的必需項,並會在您使用它時添加依賴項。 僅供參考當我遇到類似問題時提供了庫lib