了解 gruntjs registerTask 冒号

Understanding gruntjs registerTask colon

我目前正在尝试学习用于开发和生产构建的 gruntjs。

我想分配一个全局配置变量来确定内容。 我有一个简单的 initConfig :

grunt.initConfig({
  foo: {
    bar: {GLOBAL: true},
    baz: {GLOBAL: false}
  }
});

grunt.registerTask('one', ['foo:bar']);
grunt.registerTask('two', ['foo:baz']);

我的问题是:

What exactly is the colon in my tasks doing? (foo:bar or foo:baz)

And what is the difference between a colon and a simple dot?

我的目标是将全局变量设置为 truefalse 以进行进一步处理:

grunt.initConfig({
  foo: {
    bar: {GLOBAL: true},
    baz: {GLOBAL: false}
  },
  
  awesomestuff: {
    smth: GLOBAL ? 'yes' : 'no',
    another: !Global ? 'DoDebug' : 'MakeRelease'
  }
});

grunt.registerTask('one', ['foo:bar', 'awesomestuff']);
grunt.registerTask('two', ['foo:baz', 'awesomestuff']);

How would I achieve this?


更新

我让全局变量以某种方式工作。通过使用参数注册一个名为 init 的新任务,我可以在其他任务中调用它。

grunt.registerTask('init', 'Init', function(param) {
   grunt.config('GLOBAL', param)
 });


grunt.registerTask('one', ['init:true', 'foo:bar', 'awesomestuff']);

在这种情况下,将调用 init 任务并将变量 param 设置为 true。 但问题依然是:

Why would I use a colon insted of a dot to reference an object?

Why would I use a colon instead of a dot to reference an object?

要明白为什么,首先要明白g运行t task configurations and targets.

单个目标

为了帮助您进一步理解这个概念和术语,请查看名为 [=16] 的 g运行t 插件的 example 配置=].这是一个复制文件的插件。下面是该代码的片段:

grunt.initConfig({

    copy: { // <-- Task
        main: { // <-- Target
            // ... <-- other configurations go here.
        }
    }

});

在上面的这个例子中,任务被命名为copy,它包括一个名为main目标 .

要注册此 任务,您可以按如下方式进行:

grunt.registerTask('copyFiles', ['copy:main']);

然后您将通过命令行向 运行 输入以下内容:

$ grunt copyFiles

多个目标

G运行t Tasks 也可以包含多个 Target。考虑下面的示例代码:

grunt.initConfig({
    copy: {
        js: {
            // ... <-- Additional configurations for this Target go here.
        },
        css: {
            // ... <-- Additional configurations for this Target go here.
        }
    }
});

您可以通过以下方式注册上面的例子:

grunt.registerTask('copyJavaScriptFiles', ['copy:js']);
grunt.registerTask('copyCssFiles', ['copy:css']);

因此,通过命令行:

  1. 运行 $ grunt copyJavaScriptFiles会根据指定的配置复制所有的JS文件。

  2. 运行 $ grunt copyCssFiles 将根据指定的配置复制所有 CSS 文件。

如果您想同时复制 JS 和 CSS 文件,您可以按如下方式注册任务:

grunt.registerTask('copyAll', ['copy']);

您可以通过在命令行中输入 $ grunt copyAll 来 运行 它。

请注意最后一个示例中不包含任何冒号 :。 G运行t这次会运行copyTask中的所有Targets,也就是js一个和css 一个。


And what is the difference between a colon and a simple dot?

冒号

希望现在您可以了解冒号 : 的作用。它用于引用任务中的特定 Target,通常仅在 Task 具有多个 Targets 并且您想要具体参考其中之一。

简单点

简单的点是 JavaScript 访问对象属性的标准符号。 Google "JavaScript notation" 了解更多关于 圆点表示法 方括号表示法 .

在您的 Gruntfile.js 上下文中,点符号通常用于调用 grunt 对象的 functions/methods/properties。例如:

grunt.initConfig({...});

grunt.loadNpmTasks(...);

grunt.registerTask(...);

EDIT 1 在原 post/question 更新后更新了答案。