Loading HTML snippets via AMD

Topics: General
Jan 13, 2014 at 1:02 PM
A lot of our Javascript codebase consists of AMD blocks like this:
define([
  'underscore',
  'backbone',
  'text!templates/view.html'
], function(_, Backbone, template) {
  var compiled = _.template(template);
  // continues with defining Backbone view that uses the template
});
Loading underscore or Backbone through Typescript is rather trivial. The problem lies in loading templates.

The only way around this problem seems to be:
  • Create a new typescript file, template.ts - as you cannot use declare module block in the importing file
  • Declare the template as a module:
  declare module 'text!templates/view.html' {
    var template: string;
    export = template;
  }
  • Use ///<reference comment in the importing file
  • import template = require('text!templates/view.html');
This is very tedious, error-prone and promotes code duplication. Is there any language feature I am missing?
Jan 14, 2014 at 8:41 AM
There is a secret comment instruction that can add AMD dependency so you don't have to declare module anymore but still there is some boilerplate associated:
/// <amd-dependency path="text!templates/view.html"/>

declare function require(name: string): string;

var template = require('text!templates/view.html');
See this discussion: https://stackoverflow.com/questions/13906656/invoke-the-text-plugin-from-requirejs-mapping
Jan 14, 2014 at 8:52 AM
Your solution reduces the need for an additional file, but is still far from ideal - especially mixing require as a function and require as a language construct is very confusing.

I hope there will be some language feature to declare & require a module as a one-liner.
Jan 14, 2014 at 9:09 AM
Well I don't consider it a solution just a workaround :)

Another one is having one file with all require('text!...') calls (let's say template.ts) and export each template string. In this case it would be only one file with ugly syntax and the rest of the code would be clean.
Jan 14, 2014 at 9:22 AM
Yes, there seems to be no language feature that would alleviate the need for this chanting and ritual dances whenever you want to load a HTML snippet.

For future readers of this thread - this feature request is tracked by the following issue:
https://typescript.codeplex.com/workitem/1046
Mar 17, 2014 at 1:41 AM
I wrote a small story about module resolution plugins here.