0

我正在尝试使用 Grunt 来清理一个大型项目。对于这个特定示例,我正在尝试运行单元测试,并且只想对当前执行grunt目录下的路径(即 的结果pwd)执行此操作。

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

笔记:

  • 我不需要被告知“你为什么要这样做?Grunt 应该管理你的整个项目!” 这是一次改造,直到一切正常的那一天,我想要/需要它零碎的。
  • 重申"**/test/"一下,这不是答案,因为我只想要当前grunt执行目录下的测试。
  • --base也不会工作,因为 Grunt 会在基本位置查找 Node 包。
  • 对于类似的情况,我使用了一个共享配置 JSON 文件,该文件是通过grunt.config.merge(grunt.file.readJSON("../grunt-shared.json"));. 但是,这需要子文件夹中的 Gruntfiles,以及共享文件的硬编码路径(例如,../),这似乎很脆弱。
  • 我可以编写代码来进行一些目录爬升和路径构建,但我想把它作为最后的手段。
4

1 回答 1

0

这是我提出的解决方案(H/T 至 @firstdoit,https ://stackoverflow.com/a/28763634/356016 ):

  • 在项目的根目录中创建一个共享的 JavaScript 文件以集中 Grunt 行为。
  • 每个“子项目”目录都有一个最小的样板文件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));
};

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

{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;
};
于 2016-02-09T17:21:07.940 回答