Search code examples
knockout.jsrequirejsamd

Knockout AMD Module and R.js


I am using Knockout with the https://github.com/rniemeyer/knockout-amd-helpers Module binding.

<div data-bind="module: { name: baseModule, template: baseTemplate }"></div>

and in the viewModel:

_this.baseModule = ko.observable('AppViewModel');
_this.baseTemplate = ko.observable('base');

Before using the r.js optimizer everything was working properly. I had these settings and in dev environment a GET was done to the right asset (a .txt file containing the template) everytime a template was needed.

ko.amdTemplateEngine.defaultPath = "views-gulp";
ko.amdTemplateEngine.defaultSuffix = ".txt";

However now that I used r.js for production environment I thought that the .txt template would be taken into account when all is optimized in one file.

The problem: Knockout Module binding is still doing a GET to an asset which is not existing anymore (and should be in the optimized file).

Any idea :-) ?


Solution

  • The problem is the template is required at run time and is not a dependency in a define().

    In your configuration for r.js use the include option to always include the file in the build:

    https://github.com/requirejs/r.js/blob/master/build/example.build.js#L27

    Line 434

    include: ["foo/bar/bee"]
    

    If that does not work you could make a "templatesModule" that referenced all the templates and make it a dependency of app start js file.