AnarchoTroll
AnarchoTroll

Reputation: 495

Modularizing javascript code in a Rails app

I am trying to port our rails web app to ember.js (we currently do most of the work rendering views on the server side) and I was wondering how to achieve full modularization of the javascript code. So far, the plugin I liked the most was sprockets-commonjs, which automatically creates commonjs modules for all files that are named .module.js . This would solve most of our problems, except for external libraries, which would still declare globals in the code.

The only solution I can think of is to create common.js modules for each of those libraries.

E.g.: Suppose I want to be able to import Ember.js as a Common.js module. I would then create a file called vendor/modules/ember.module.js, that would contain the following:

//= require ember

module.exports = Ember;

I would then import ember_module (along with the rest of the module wrappers) to the application and use them.

//= require_tree vendor/modules

var ember = require("vendor/modules/ember");

This solution is kinda hacky, but it would improve the modularization of the code. Is there a better way to achieve the same results?

Upvotes: 0

Views: 767

Answers (1)

davidjbeveridge
davidjbeveridge

Reputation: 31

In your ember.module.js, try using //= include ember rather than require. The require directive just adds the file as a dependency; the include directive will actually include the file contents in-place. (See https://github.com/sstephenson/sprockets#sprockets-directives).

Otherwise your solution should work :)

Upvotes: 3

Related Questions