Grunt task to resolve require tags in JavaScript files
The following file app.js
requires the file controller.js
to be prepended:
//= require "controller.js"
var controller = new controller.Controller({
container: "#page-container"
});
This is controller.js
to be prepended to app.js
.
(function (global) {
global.controller = {
Controller: function Controller(spec) {
this.container = $(spec.container);
}
};
}(this));
Have grunt-resolve
in your package.json
{
"name": "your-project-name",
"version": "0.1.2",
"devDependencies": {
"grunt": "~0.4.1",
"grunt-resolve": "~0.1.0"
}
}
In the Gruntfile.js
we put now
grunt.initConfig({
[...]
resolve: {
files: [ "src/app.js" ]
}
});
grunt.loadNpmTasks('grunt-resolve');
This will create dist/app.js
with the concatenated source code. resolve resolves files recursively, normalizes multiple dependencies from and to a given file, skips declared dependencies not found on disk and is robust concerning circular dependencies (does not loop).
In a JavaScript file one or more require
lines can be added:
//= require "dep1.js"
//= require "dep2.js"
All require lines of a file are gathered, hoisted to the top of the file and recursively resolved for transitive dependencies.
Multiple files can be listed separated by commas:
//= require "dep1.js, dep2.js"
Dependencies are relative to the source file containing the require line:
//= require "dep1.js, modules/module-1.js, ../common/extend.js"
The complete configuration options are as follows:
grunt.initConfig({
resolve: {
files: [ "src/app.js", "modules/google-analytics.js" ],
dist: "outputdir",
exclude: {
"src/app.js": ["Spec\\.js$", "test-*\\.js$"]
}
}
});