使用执行目录作为 Gruntfile 的文件库

using execution directory as Gruntfile's file base

我正在尝试使用 G运行t 来清理一个大型项目。对于这个具体的例子,我正在尝试 运行 单元测试,并且想 用于当前 grunt 执行目录下的路径(即结果pwd).

我想在项目根目录下创建一个 G运行t 文件。我知道 grunt 会从任何子目录中毫无问题地找到并执行它。如果我将我的测试 运行 选项定义为在 "test/" 中查找,它只会在 {project root/}test/ 下进行 运行s 测试。有没有办法告诉项目级 G运行tfile 使其路径(全部或部分)相对于执行位置?

备注:

这是我想出的解决方案(H/T @firstdoit,):

  • 在项目的根目录创建一个共享的 JavaScript 文件以集中 Grunt 行为。
  • 每个 "sub-project" 目录都有一个最小的样板文件 Gruntfile.js
  • 在共享文件中手动调整 Grunt 的文件库以从一个 node_modules 源加载。

Gruntfile.js

/**
 * This Gruntfile is largely just to establish a file path base for this
 * directory. In all but the rarest cases, it can simply allow Grunt to
 * "pass-through" to the project-level Gruntfile.
 */
module.exports = function (grunt)
{
    var PATH_TO_ROOT = "../";

    // If customization is needed...
    // grunt.config.init({});
    // grunt.config.merge(require(PATH_TO_ROOT + "grunt-shared.js")(grunt));

    // Otherwise, just use the root...
    grunt.config.init(require(PATH_TO_ROOT + "grunt-shared.js")(grunt));
};

PATH_TO_ROOT 使用 var 在很大程度上是不必要的,但它为跨子项目使用此样板文件提供了一个单一的焦点。

{ROOT}/grunt-shared.js

module.exports = function (grunt)
{
    // load needed Node modules
    var path = require("path");

    var processBase = process.cwd();
    var rootBase    = path.dirname(module.filename);

    /*
     * Normally, load-grunt-config also provides the functionality
     * of load-grunt-tasks. However, because of our "root modules"
     * setup, we need the task configurations to happen at a different
     * file base than task (module) loading. We could pass the base
     * for tasks to each task, but it is better to centralize it here.
     *
     * Set the base to the project root, load the modules/tasks, then
     * reset the base and process the configurations.
     *
     * WARNING: This is only compatible with the default base. An explicit base will be lost.
     */
    grunt.file.setBase(rootBase);
    require("load-grunt-tasks")(grunt);

    // Restore file path base.
    grunt.file.setBase(processBase);

    // Read every config file in {rootBase}/grunt/ into Grunt's config.
    var configObj = require("load-grunt-config")(grunt, {
        configPath: path.join(rootBase, "grunt"),
        loadGruntTasks: false
    });

    return configObj;
};