What’s Tripping Up Uglifier?

jsrn profile image James Originally published at jsrn.net on ・1 min read

In production mode, Rails 4 uses the uglifier gem to compress your JavaScript code into something nice and small to send over the wire. However, when you’ve got a syntax error, it can fail rather… ungracefully.

You get a big stack trace that tells you that you’ve got a syntax error. It even helpfully tells you what the error was! Unexpected punctuation. There’s a comma, somewhere. Where? Who knows. It doesn’t tell you.

If you have a large project, or have multiple people making large changes, it can be a little time consuming checking the diffs of recent commits to figure out where the error was introduced. Here is how you can use the rails console to at least find the offending file:

Since the uglifier doesn’t run in development, let’s drop into the rails console in production mode:

RAILS_ENV=production rails c

Now we can use the following snippet of code to find our errors:

# Take each javascript file...
Dir["app/assets/javascripts/**/*.js"].each do |file_name|
    # ... run it through the uglifier on its own...
    print "."
  rescue StandardError => e
    # ... and tell us when there's a problem!
    puts "\nError compiling #{file_name}: #{e}\n"

This saved me a little time recently, so I hope it will be handy to someone else.


Editor guide
abhishekcghosh profile image
Abhishek Ghosh

Nice! A slightly alternative way that's worth looking, to help avoid problems (more than just syntax errors) with JS code before we attempt to productionize them by running through minifiers or concatenators is to run the project's JS files through some sort of linter first (jslint, jshint, eslint... whatever works for you). This way it not only points out the errors in detail in specific files and line numbers but also forces us to maintain consistent coding and follow some best practices for large codebases :)

qm3ster profile image
Mihail Malo

I can't imagine writing without a linter.
It's probably about errors introduced by merges.

bengreenberg profile image
Ben Greenberg

This is really helpful advice. I'm going to bookmark it for when I'll inevitably need it one day!