像node.js一样包含CoffeeScript类

Include CoffeeScript classes like in node.js

本文关键字:一样 包含 CoffeeScript node js      更新时间:2023-09-26

我刚刚开始使用CoffeeScript,我已经被类困住了。我想让我的文件结构像在节点,这样我就可以要求一个JavaScript文件包含这样的类。

Test = require "test.js"

Test.start()

其中start是Test类的一个方法。

这可能吗?

这可能吗?

与Node中的不完全相同。浏览器环境中没有同步的require。然而,您可以尝试许多异步库中的一个来实现这一点,看看AMD。最著名的实现是require.js.

我发现在浏览器环境中使用CommonJS模块(Node.js使用的模块)的最简单方法是使用Browserify。我个人也更喜欢CommonJS模块定义的AMD的,但这只是个人的品味。

另外,考虑到为了导出您的类,以便require 'test'将直接给您类构造函数,您必须将您的类分配给module.exports:

# In test.coffee
module.exports = class Test 
  @start = -> console.log 'start!'

然后编译该文件到test.js,你就可以使用它了:

Test = require './test'
Test.start()

在Node.js中,这将只是工作。在浏览器中,您需要首先使用Browserify(或其他工具)处理文件以使其工作(它将创建适当的require函数以及一些exportsmodule.exports变量,以便CommonJS模块正确工作)。

看看stitch, hem(灵感来自stitch,但有更多整洁的功能)和browserify。

我个人更喜欢下摆。你可以这样做:

# app/lib/model.coffee
module.exports = class Model
  ...

.

# app/lib/util.coffee
helper1 = -> ...
helper2 = -> ...
module.export = {helper1, helper2}

.

# app/index.coffee
Model = require 'lib/model'
{helper1} = require 'lib/util'
# do whatever you want with required stuff
...

Hem负责动态编译CoffeeScript,并将所有需要的代码捆绑在一起(它还支持npm模块和任意js库作为代码的外部依赖项,更多细节请参阅文档)。