requirejs-rails AMD error "two many anonymous modules in it"

282 Views Asked by At

Attempting to precompile my Backbone assets using requirejs-rails (using Rails 4). I keep hitting a roadblock that require-js complains that

Error: Error: application.js has two many anonymous modules in it.

This appears to be a RequireJS error. Googling finds this Github issue, which I don't understand.

I did discover that the problem lies in any libraries that have AMD conditionals at the head like the example below. I imagine it has something to do with registering itself as an anonymous module. If I remove these conditionals then requirejs-rails no longer complains and I can compile the optimized file which then works within Rails.

But manually removing these AMD conditionals from all my external libraries is not sustainable.

Anyone have a better suggestion? My requirejs.yml file is properly setup.

Note: I'm using this fork of requirejs-rails since the main code does not work with Rails 4.

As an aside: I'm able to use the same code without removing the AMD bits in a non-Rails application calling r.js directly (instead of requirejs-rails) to optimize the code. I'm not sure why requirejs-rails' optimization is tripping up on this error when r.js did not. I thought requirejs-rails is calling r.js underneath?

Example of what is causing the error:

(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
    // AMD. Register as an anonymous module.
    define( [ "jquery" ], function ( $ ) {
        factory( $, root, doc );
        return $.mobile;
    });
} else {
    // Browser globals
    factory( root.jQuery, root, doc );
}
}( this, document, function ( jQuery, window, document, undefined ) {
1

There are 1 best solutions below

0
On

For what it's worth I discovered how to get around this particular problem. The issue lies in the version of r.js that's bundled with the requirejs-rails gem. When I swapped out the v2.1.2 r.js located in .bundler/ruby/2.0.0/requirejs-rails-e0932125e1d5/bin/ with the v2.1.10 located here I no longer received the "two many anonymous modules" error and was eventually able to build the optimized application.js file.

That being said, I eventually ran into more issues related to the requirejs-rails operation. One look at the requirejs-rails Issues page and you can see there are some resourcing issues with the project. I will likely be abandoning Requirejs for my Rails project - someone has yet to find an elegant solution for working with the Rails 4 asset pipeline.