javascriptrequirejsrequirejs-text

RequireJS - custom paths and the text! plugin


I'm working on a SPA, and have optimized one of my code files with the requireJS optimizer, and set the new path like this:

config.paths['billingmanager/billing/billing'] = 'billingmanager/billing/billing-build';

Unfortunately, code that now (conceptually) does this

require(['text!billingmanager/billing/billing.htm'], callback);

now attempts to find billingmanager/billing/billing-build.htm and fails miserably.

Can can I tell text! that, no matter how the normal require path for billingmanager/billing/billing is set, I want you to fetch the file billingmanager/billing/billing.htm—period.

I do have a workaround, to do something like this

config.paths['billingmanager/billing-htm'] = 'billingmanager/billing/billing.htm';

and then manually know to use require(['text!billingmanager/billing-htm']); but I'm really hoping there's a simple fix here.


Solution

  • I've not run into this specific problem but the first thing I'd do to work around it would be to replace the path I give to text! with a relative path, which should avoid the clash with the path you've got in your paths. So, for instance:

    require(['text!../parent/billingmanager/billing/billing.htm'], callback);
    

    Of course the actual relative path you should use depends on the architecture of your application. It turns out that just using ./ won't be enough to work around RequireJS' cleverness so in the illustration above, I'm backing out of the current directory and then going back in. I've assumed that the current directory is name parent.

    Note that the rules for path resolution for the path given to text! is different than the regular path resolution rules. Normally, adding an extension to a path given to require will completely bypass the paths setting. So require(['billingmanager/billing/billing/foo.js']... will look for a file named billingmanager/billing/billing/foo.js relative to baseUrl and will not use the paths setting you've shown in the question. This is not the case for paths given to text!. These paths go through the paths setting even if they have an extension. (This is documented here.)