0

Somehow in development environment my coffeeScript files compile correctly. But when I compile them for production I get something like this

CoffeeScript:

$->
  alert "hello world"

Compiled to Javascript

(function() {
   $(function(){
      alert("hello world");
   })
}).call(this)

I have checked for miss indentations and spacing errors, or for a mix of tabs and spaces but there are not any. The weird thing is that when I converted the with the compiler from coffeescript.org it compiles correctly, its just in the production environment. Any ideas?

by the way: I am using rails 4

j-f
  • 53
  • 7
  • It's a setting, the (function()... is a closure to avoid declaring global variables. It's ok and you should keep it anyway. – Francesco Belladonna Nov 07 '13 at 17:50
  • ["Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: `(function(){ ... })();` This safety wrapper, combined with the automatic generation of the `var` keyword, make it exceedingly difficult to pollute the global namespace by accident."](http://coffeescript.org/#lexical-scope) – mu is too short Nov 07 '13 at 18:07
  • That's exactly the correct compiled output, and it's definitely not a "compile error". – user229044 Nov 07 '13 at 18:23
  • @Fire-Dragon-DoL actually in development its more like $(function() {return alert("hello world");}); The issue I have with this is that its not called when the document is loading. – j-f Nov 07 '13 at 18:28
  • @Fire-Dragon-DoL was correct. This is a feature not an error. What was actually going wrong was that the production server hadn't precompiled the assets. Thanks for the help. – j-f Nov 07 '13 at 18:37

1 Answers1

0

It's a coffeescript setting.

(function() {
  # Code here
}).call(this)

Is a closure generated by coffeescript by default (can be disabled, but you shouldn't), used to avoid global namespace pollution.
It doesn't affect the script execution, your jQuery code will still be run once document is loaded.

Important note
The only issue you may find with that closure is that you actually have hard time declaring global variables. This can be solved in this way:

window.yourvar = 'something'

There is also a suggestion here on how you can disable it anyway: How can I use option "--bare" in Rails 3.1 for CoffeeScript?

Community
  • 1
  • 1
Francesco Belladonna
  • 11,361
  • 12
  • 77
  • 147