Transitioning to Modules With Global Imports

Written by Pete Corey on May 9, 2016.

Meteor 1.3 is upon us! It brings with it promises of better testability, reusability and debugability all thanks to the ES6 module system.

Unfortunately, a wholesale transition into the 1.3-style of doing things may take a huge amount of work, depending on the size of your application. Where will you find the time to refactor your entire application into modules?


Even a partial transition can be frustrating.

Imagine you have a collection called MyCollection that you’ve decided to move into a module. This process is simple enough. After your refactor, you might have a module located at /imports/lib/mycollection that exports MyCollection:

import { Mongo } from "meteor/mongo";
export default new Mongo.Collection("mycollection");

The difficulty comes in when you realize that the rest of your 1.2-style application still assumes that this collection will be accessible as a global reference.

When you run your application, you’ll be greeted by countless errors complaining that MyCollection is not defined throughout your application:

ReferenceError: MyCollection is not defined

One possible solution to this problem is to find each file referencing this collection and import MyCollection module within it.

import MyCollection from "/imports/lib/mycollection";
...
MyCollection.find(...);

However, if your application references this collection throughout dozens or hundreds of files, this can quickly get out of hand. The seemingly simple process of moving MyCollection into a module has suddenly turned into a hydra requiring you to edit files throughout your entire project.


Another solution to this problem is to import MyCollection globally on both your client and your server. This eliminates the need to modify potentially hundreds of files throughout your project, and lets your legacy 1.2 code exist in blissful harmony with your 1.3 modules.

But how do we import modules globally? It’s not as simple as just importing them in your project’s main.js files. After all, ES6 import calls are transpiled down to var declarations by Babel, and var scope is limited to the file it was declared in.

The key is to import your module into your local scope and then explicitly assign it to a global reference. Using this technique, your client/main.js and server/main.js would look something like this:

...
import _MyCollection from "/imports/lib/mycollection";
MyCollection = _MyCollection;

If your collection is a named export, rather than a default export, you can assign it to a global reference like this:

import { MyCollection as _MyCollection } 
       from "/imports/lib/mycollection";
MyCollection = _MyCollection;

Transpired down to ES5, our import looks something like this:

var _mycollection = require("/imports/lib/mycollection");
MyCollection = _mycollection.MyCollection;

Notice that we’re reassigning the locally scoped _mycollection to the global MyCollection reference. Now, your old 1.2 style code can continue to reference MyCollection as a global.

Happy refactoring!

Meteor Unit Testing With Testdouble.js

Written by Pete Corey on May 2, 2016.

It’s been several months since my first post on unit testing with Meteor 1.3, and Meteor 1.3 has finally been officially released!

With this release, Meteor’s new recommending testing solution is the all-in-one meteor test command. When you run your application with meteor test, it spins up your application server, but only loads your test files and modules explicitly imported by your tests. In theory, you can run your unit tests, integration tests, and (with an extra flag), your end-to-end tags with this tool.

Unfortunately, there is a problem. meteor test is slow! Spinning up a server is fantastic for end-to-end and integration tests, but is a massive hinderance when trying to write fast unit tests.

As I mentioned in my last post, I can easily find myself lost on Twitter by the time my server restarts.

Dependency Injection Woes

Recently, I’ve been getting feedback from people who read my Unit Testing With Meteor 1.3.

They like the idea of using Mocha directly and bypassing meteor test for faster unit test turnarounds, but find the dependency injection technique I described to be too much work in practice. But without dependency injection, how do we get around Meteor’s “magic imports”?

Error: Cannot find module 'meteor/meteor'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:289:25)
at Module.require (module.js:366:17)
at require (module.js:385:17)

This error may be familiar to you if you’ve ever tried to evaluate Meteor-style modules outside the context of the Meteor build tool.

Hooking and Stubbing

Thankfully, there are ways around these tricky imports that don’t require a cumbersome dependency injection architecture.

What if we could just hook into each import and require call, and return our own objects whenever we detect an import of the "meteor/meteor" module? We could even return a Meteor object filled with stubbed or mocked methods so we can make assertions about how and when those methods are called!

The good news is that this is entirely possible within Node.js; there are actually multiple ways of accomplishing this.

In this post on the Meteor forums, Stephan Meijer discussed one technique for doing exactly this using require-hook and Sinon.js. While this technique works beautifully, I’ve recently been playing with replacing both of these modules with Testdouble.js in my testing infrastructure.

Enter Testdouble.js

Testdouble.js lets us easily replace modules with fully stubbed replacements. For example, replacing the "meteor/meteor" with an object with stubbed out methods and call functions is as simple as:

import td from "testdouble";
let Meteor = td.object(["methods", "call"]);
td.replace("meteor/meteor", { Meteor });

After this point, any imports of the "meteor/meteor" module will be given our test double, rather than the real "meteor/meteor" module.

We can even use Testdouble.js to make assertions about how our stubbed methods have been used:

...
thisMethodCallsFooWithBar();
td.verify(Meteor.call("foo", "bar"));

If thisMethodCallsForWithBar did not call the "foo" Meteor method with an argument of "bar" (e.g., Meteor.call("foo", "bar");), our td.verify assertion would fail.

Fast, Simple Unit Testing

I’ve created an example Meteor application that demonstrates these ideas. Check it out on Github. Be sure to take a look at the module under test and the tests themselves.

You can run the Mocha unit tests once:

npm test

Or you can tell Mocha to watch your project for changes and re-run your test suite on each change:

npm test -- -w

I’ve also included a short video showing how I might interact with my test runner. I make a change to a test, instantly notice that the test fails, find the problem, and notice that the test turns green as soon as I make the fix.

As you can see, the results of my test suite appear nearly instantly after every file change.

Sweet relief!

Credit Where Credit Is Due

Credit for this post goes to Stephan Meijer and the amazing work that he posted to the Meteor forums.

Stephan outlines how to mock Meteor dependencies using both require-hook and Sinon.js, and the Testdouble.js technique described above. He even found and documented a workaround for an issue related to ES6 import hoisting that was preventing Testdouble.js from properly replacing modules.

Awesome work, Stephan!

Blaze Meets Clusterize.js

Written by Pete Corey on Apr 18, 2016.

Recently, I’ve been working on a Meteor project that deals with lots of data. Most of this data is rendered in “cards” that populate a vertically scrolling list.

These cards need to be very quickly scannable, sortable, and filterable by any users of the application. To do this quickly, we need to publish all of this data to the client and let the UI handle its presentation; we can’t rely on techniques like infinite scrolling or on-the-fly subscriptions.

This situation led to an interesting problem with Blaze and an even more interesting solution leveraging Clusterize.js and a client-side cache. Let’s dig into it!

Blazingly Slow

The naive Blaze solution to presenting a bunch of UI components is to simply render each of these cards within an {{#each}} block:

{{#each data in cards}}
  {{> card data}}
{{/each}}

Unfortunately, as we start to render (and re-render) more and more cards in our list, or application slows to a crawl. After lots of profiling, debugging, and researching I came to the conclusion that Blaze simply isn’t designed to handle this much rendering and re-rendering.

Arunoda of MeteorHacks (partially) explains the issue in this article and its corresponding blog post.

Enter Clusterize.js

For our situation, a better approach was to use Clusterize.js to efficiently manage and render the massive list of cards.

Rather than dumping all of our cards into the DOM at once, Clusterize.js only renders the small portion of the cards that are currently visible. As you scroll through the list, those DOM elements are recycled and replaced with the newly visible cards. This efficient use of the DOM makes Clusterize a much more effective option when dealing with large sets of scrolling data.

Unfortunately, using Clusterize.js with Blaze wasn’t the most straight-forward process. Here’s a breakdown of how I approached the problem.

I didn’t want this Clusterize.js implementation code to permeate the rest of my front-end code, so I decided to abstract all of the Clusterize-specific complexity I was about to introduce into its own private Blaze component. This component introduced some boilerplate DOM elements required by Clusterize and an onRendered hook required to initialize the plugin:

<template name="clusterize">
  <div id="scrollArea">
    <div id="contentArea" class="clusterize-content">
    </div>
  </div>
</template>
Template.clusterize.onRendered(function() {
  // Initialize Clusterize.js here...
  this.clusterize = undefined;
});

The component was designed to accept a cursor and a template name. Each document returned by the cursor was associated with a single card that needed to be rendered with the given template. We could use the component like this:

{{> clusterize cursor=getCardDocuments
               template="card"
               options=getClusterizeOptions}}

Where getCardDocuments was a helper that returned a cursor, and getClusterizeOptions returned an options object to be passed into Clusterize.js.

Basic Rendering

The most straight forward way of using Clusterize.js is to render our cards in the DOM using a Blaze ``{:.language-javascript} tag, and then initialize the plugin:

<div id="contentArea" class="clusterize-content">
  {{#each document in cursor}}
    {{> Template.dynamic template=template data=document}}
  {{/each}}
</div>

Unfortunately, this leads to the same problems that started this whole mess. Naively rendering lots of templates in Blaze is inherently slow!

Another technique would be to manage the rendering process ourselves and give Clusterize.js a list of raw HTML strings to manage and render:

Template.cachedClusterize.onRendered(function() {
  this.autorun(() => {

    // Any time data changes, re-run
    let data = Template.currentData();
    if (!data) {
      return;
    }

    // Build the HTML for each patient card
    let template = Template[data.template];
    let rows = data.cursor.fetch().map(function(document) {
      return Blaze.toHTMLWithData(template, document);
    });

    // Update or initialize Clusterize.js
    if (this.clusterize) {
      this.clusterize.update(rows);
    }
    else {
      this.clusterize = new Clusterize(_.extend({
        rows: rows,
        scrollElem: this.$("#scrollArea")[0],
        contentElem: this.$("#contentArea")[0]
      }, data.options));
    }

  });
});

This seems like a step in the right direction, but as the cursor changes, you might notice that our component takes quite a bit of time to re-render each of the cards before passing the raw HTML off to Clusterize.js…

There has to be a faster way!

Cached Rendering

Thankfully, speeding up this implementation was fairly straight-forward. The key insight is that we don’t want to waste time re-rendering a card if we’ve already rendered it in the past. This sounds like an ideal job for a cache!

In this case, I decided to use a simple LRU cache (specifically, lru-cache) to cache my rendered templates. This cache can be set up in your application in a variety of ways depending on your current Meteor version.

I decided that a simple, but effective caching strategy would be to store each card’s rendered HTML string in the cache, indexed by the card’s _id.

This change makes the Clusterize.js render method slightly more complex:

...
let rows = data.cursor.fetch().map(function(document) {
  // Has this card already been rendered?
  let html = TemplateCache.get(document._id);
  if (html) {
    return html;
  }

  // Render the card and save it to the cache...
  html = Blaze.toHTMLWithData(template, document);
  TemplateCache.set(document._id, html);
  return html;
});
...

Now, if we ever try to re-render a card that’s already been rendered on the client, we’ll find that card in the cache and instantly return the card’s rendered HTML.

This greatly improves the speed of our Clusterize.js component as we change the set of cards we’re trying to render.

Cache Invalidation

Unfortunately, our Clusterize.js component in its current form has some major issues.

If we ever update any data on a document that should be reflected on that document’s card, we’ll never see that change. Because that card has already been rendered and cached, it’ll never be re-rendered. We’re stuck looking at old, stale data in our cards list.

To deal with this situation, we need to clear any cache entries for a card whenever its corresponding document is changed. The most straight-forward way of doing this is through an observe handler on the cursor provided to our component:

...
// Invalidate our cache whenever a doucment changes
data.cursor.observe({
  changed: function(id) {
    TemplateCache.del(id);
  }
});
...

Bam! We now have incredibly fast, dynamically updating cards in our Clusterize.js managed list!

Next Steps

What I described here is a fairly simplified version of the Clusterize.js component I finally landed on.

This version doesn’t handle “client-side joins” within your rendered cards. It also doesn’t handle changes made to documents on the server, while that document doesn’t exist in the client’s cursor. These downfalls can easily be addressed with slightly more sophisticated invalidation rules and caching schemes.

At the end of the day, Clusterize.js was a life saver. With some minor massaging, it was able to step in and replace Blaze to do some majorly impressive feats of rendering.