Last Updated: February 25, 2016
·
2.488K
· imakewebthings

Using RequireJS Map Config with Text Plugin

One of my current for-hire projects is built with Backbone and RequireJS. We needed the ability for client builds of the app to replace individual modules with their own customized version. Require's map config is a natural fit:

map: {
  '*': {
    'views/foo': 'client/views/foo'
  }
}

But I ran into a snag when trying to do this map replacement with templates using the text plugin.

map: {
  '*': {
    'templates/foo': 'text!client/templates/foo.html'
  }
}

// In the module...
define('templates/foo', function(template) { ... });

This produces 404 errors as the loader tries to load baseURL/text!client/templates/foo.html.js. In retrospect, this result speaks to how the plugin system works with Require, but I took the hard way and tried all sorts of combinations to get the mapping to work. Move text! here. Drop .html there. In the end, the answer is:

map: {
  '*': {
    'templates/foo': 'client/templates/foo.html'
  }
}

// In the module...
define('text!templates/foo', function(template) { ... });

The plugin identifier (text!) should be included in the modules themselves, followed by the map key. This makes sense. Require parses the plugin identifier out of the module name first, before mapping takes place.

Hopefully this tip can save somebody else a few headscratching minutes.