简体   繁体   中英

Include CoffeeScript classes like in node.js

I am just getting use to CoffeeScript and I have gotten stuck with classes. I want to have my files structured like in node so that I can require a JavaScript file containing a class like this.

Test = require "test.js"

Test.start()

Where start is a method of the Test Class.

Is this possible?

Is this possible?

Not exactly like in Node. There is no synchronous require in browser environments. Yet, you could try one of the many asynchronous libraries to do that, have a look at AMD . The most famous implementation is require.js .

I've found that the simplest way to use CommonJS modules (the ones that Node.js uses) in browser environments is to use Browserify . I personally also prefer the CommonJS module definitions to the the AMD ones, but that's just personal taste.

Also, take into account that in order to export your classes so that require 'test' will give you the class constructor directly, you would have to assign your class to module.exports :

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

Then compile that file to test.js and you're ready to use it:

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

In Node.js this will Just Work. In browsers, you will need to process the files first with Browserify (or some other tool) to get it working (it will create the proper require function as well as some exports and module.exports variables for CommonJS modules to work correctly).

Take a look on stitch , hem (which is inspired by stitch, but has more neat features) and browserify .

Personally, I prefer hem. You can do something like this with it:

# 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 takes care of compiling CoffeeScript on the fly and bundling all the needed code together (it also supports npm modules and arbitrary js libs as external dependencies for your code, see the docs for more details).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM