Inlining require.js text! using Grunt

纵然是瞬间 提交于 2019-11-29 17:57:02

问题


I've been experimenting with Grunt and Require JS this afternoon. I'm a big fan of the text module and use it to bring in my templates. In non-Grunt based projects I used the inlineText and stubModules Require JS options to in-line the template files and it works great. However, I'm having trouble getting this to work with Grunt.

Require Config

require.config({
    paths: {
        // Using Bower for dependency management
        text: '../components/requirejs-text/text'
    }
});

Usage

define(['text!template.html'], function (html) {
    // Do stuff with html
});

Gruntfile.js

requirejs: {
    dist: {
        options: {
            baseUrl: 'app/scripts',
            optimize: 'none',
            preserveLicenseComments: false,
            useStrict: true,
            wrap: true,
            inlineText: true,
            stubModules: ['text']
        }
    }
}

After running grunt I get various errors in the console:

  • A File Not Found on /dist/components/requirejs-text/text.js
  • A Load timeout for modules: text!template.html_unnormalized2

Two issues then:

  • It doesn't seem to be inlining (and then stubbing) the text.js code
  • It doesn't seem to be inlining the template.html file

Any ideas why it's not working?


回答1:


You see the error because you need to indicate to r.js where is the text module.

You can do that by adding a paths configuration:

requirejs: {
    dist: {
        options: {
          baseUrl: 'app/scripts',
          optimize: 'none',
          preserveLicenseComments: false,
          useStrict: true,
          wrap: true,
          inlineText: true,
          stubModules: ['text'],
          paths: {
             'text': 'libs/text' // relative to baseUrl
          }
       }
    }
}

Then you'll need to download the text.js module into the appropriate directory.

But why your require.config is not working?

Because the r.js needs to evaluate the configuration at some point. You didn't mention in the question where is your require.config, but in case that you want to evaluate it you need to indicate where is to r.js (see https://github.com/jrburke/r.js/blob/master/build/example.build.js#L35):

requirejs: {
    dist: {
        options: {
          baseUrl: 'app/scripts',
          optimize: 'none',
          preserveLicenseComments: false,
          useStrict: true,
          wrap: true,
          inlineText: true,
          stubModules: ['text'],
          mainConfigFile: '../config.js' // here is your require.config

          // Optionally you can use paths to override the configuration
          paths: {
             'text': 'libs/text' // relative to baseUrl
          }
       }
    }
}


来源:https://stackoverflow.com/questions/15866683/inlining-require-js-text-using-grunt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!