Reputation: 7892
I have a module:
# a.coffee:
@f = -> console.info 'Hell, oh, world!' # Note that exports == this
and another module from which I require it:
# b.coffee:
a = require './a'
a.f()
I want to run the code in b.coffee
without an explicit build step for generating an a.js
.
In NodeJS, all I need to do is require('coffee-script')
once before anything else.
Is there an equivalent trick for the browser?
Upvotes: 0
Views: 1263
Reputation: 25718
Browsers don't natively support coffeescript. If you just want to be able to make changes to a coffee file and reference it without having to manually run a command each time, you can use the coffee compiler to watch the file and update a js file as you make changes to it.
coffee --watch --compile experimental.coffee
There will have to be a step where a js file is created and referenced when working in the browser though.
Since you want a library to support commonjs modules anyway, you might want to look into browserify. It has support for something like what you want to do with its transform function: https://github.com/substack/node-browserify#btransformtr.
This may never be quite as nice as you'd like it though. The compilation process has to happen for a browser to read coffeescript. For performance reasons its going to be much better if that happens on the server, rather than on the client where you're using the users time every single time!
The compilation can be simple. Since you want to have static files only on the server, its trivial to write a script that takes all your coffee files, bundles them into a compressed js file, and then you can reference that file in your html. That can be done with the coffee compiler or a build tool like grunt.
Upvotes: 1
Reputation: 17505
Before I tell you how, I want to make it clear that no one should ever do this in anything that even remotely resembles a production environment, since this forces each browser to compile it on every page load. With that in mind:
Check out http://jashkenas.github.io/coffee-script/#scripts. If you put the CoffeeScript compiler in your page via a script tag, then you can include CoffeeScript files (or even inline source) with a <script type="text/coffeescript">
tag. Script will be compiled and run in the order they appear in the html.
Upvotes: 3