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?
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