requirejsrequirejs-text

How does the text! plugin use the baseUrl?


I'm having an issue getting the text! plugin to work in my requirejs site. It's always including lib/ in the request url, however all of the other files (not using text!) are being successfully found and loaded. Here is my directory structure:

WebContent/
  |--backbone/
        |--Bunch of folders and files
  |--config/
        |--config.js
  |--lib/
        |--jquery.js
        |--text.js
        |--require.js
  |--index.html

my index.html file is:

<body>
    <div id="siteLayoutContainer"></div>
    <script data-main='config/config' src="lib/require.js"></script>
</body>

The config file is:

requirejs.config({
    baseUrl: './',
    paths: {
        jquery: 'lib/jquery.js',
        backbone: 'lib/backbone.js',
        text: 'lib/text',
        application: 'backbone/application'
    },
    text: {
        env: 'xhr'
    }
});
require(['application'], function(App) {
    App.start();
});

I'm using the text! plugin like so:

define([
    'jquery',
    'text!backbone/templates/SomeTemplate.html'
], function(jQuery, NotFoundHtml) {
    //Some code here
}

So, in the above script, the url being used for the template is: http://localhost/lib/backbone/templates/SomeTemplate.html

and I am expecting it to be: http://localhost/backbone/templates/SomeTemplate.html

I've tried the following:

So I'm stuck and can't figure out what I'm missing. I'm obviously not understanding how the text! plugin uses the baseUrl or how it determines the url it's going to use to fetch the defined file.


Solution

  • After your edits to your question, it now contains all the information to diagnose the problem. As you guessed in one of your comments, the issue is indeed that this path:

    backbone: 'lib/backbone.js',
    

    is throwing off the resolution of the template you give to the text plugin. When the text plugin loads what you give to it, it takes the path after the ! symbol and treats it as if it were a module name, and it goes through the module resolution process. The way module resolution works is that it checks if there is a prefix that matches any of the keys in paths and will change the prefix with the value associated with the key, which gives the result you obtained. One way to fix the issue would be to add this to your paths configuration:

    "backbone/templates": "backbone/templates"
    

    This will make it so that anything you request under backbone/templates won't get messed up by the backbone path.

    Note: it is preferable to avoid putting extensions in module names so you should remove it from the values you have for jQuery and Backbone.