2012-03-30 32 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