How can I completely disable CoffeeScript in a Rai

2020-01-28 06:21发布

问题:

At the moment when I generate a new controller, Rails also generates a .js.coffee file for the controller as well. As I don't use CoffeeScript I want Rails instead generate .js files for me.

Is it enough to comment out the coffee-rails gem to completely disable CofeeScript in a Rails 3.1 app?

回答1:

  1. Comment out gem "coffee-script" in your Gemfile
  2. Use .js instead of .js.coffee for your javascript files


回答2:

Not sure if this counts for Rails 3.1 but in 4 you should also set the javascript_engine to :js in application.rb to instruct generators to create .js files instead of .js.coffee.

config.generators do |g|
  # .. other configuration ..
  g.javascript_engine :js
end


回答3:

Koen and Gaurav Gupta have good answers!

If you want to make these changes automatically for every new Rails project, you can use a template file.

In ~/rails-template.rb

# Don't install coffeescript
gsub_file 'Gemfile', /^gem \'coffee-rails\'/ do
  "\# gem 'coffee-rails'"
end

# Mess with generators to get the behavior we expect around new files
# For these injections, indentation matters!
inject_into_file 'config/application.rb', after: "class Application < Rails::Application\n" do
  <<-'RUBY'
    config.generators do |g|
      # Always use .js files, never .coffee
      g.javascript_engine :js
    end
  RUBY
end

Then in ~/.railsrc

-m ~/.rails-template.rb

Now whenever you run rails new, the coffeescript gem will be commented out, and new controllers will use .js instead of .coffee.

Tested on Rails 5.0.4, but I believe it should work for earlier versions as well.


As an aside, Rails templates, and generators in general, are super powerful. I'm a teacher and my students will typically create 15 to 20 rails projects through the course, and providing them with a good template file with debugging gems, spec style testing, etc. is a huge timesaver. After they've made the changes once themselves, of course. If you're interested, my personal .rails-template.rb is on GitHub.



回答4:

Note for Rails 4, or if you're using 'turbolinks', 'uglifier', or any other kind of gem that requires the server to interpret javascript, comment them out as well.



回答5:

I had this problem, as I am using codekit to compile my coffeescript.

I got around it by renaming my 'assets/coffee' folder to 'assets/cafe', so rail wouldn't find it.

Edit: What does work (and the ONLY thing that works for me, the above answer does not work) is to add a separate folder 'App/Coffee', and setting it to be compiled into the assets/javascript folder. If it's in the assets directory, rails will find it no matter the name.