Grunt-创建任务
时间:2020-02-23 14:33:23 来源:igfitidea点击:
在本教程中,我们将学习为Grunt创建简单的任务。
创建我们的第一个Grunt任务
让我们创建一个简单的任务,当在命令行上运行grunt时,它将打印" Hello World"。
打开在入门教程中创建的Gruntfile.js文件,然后执行以下代码。
module.exports = function(grunt) {
/**
* this will print "Hello World"
* when we run
* $grunt greetings
* on command line
*/
grunt.registerTask("greetings", function() {
console.log("Hello World");
});
};
因此,在上面的代码中,我们创建了模块,并使用grunt的registerTask方法创建了第一个任务问候。
该任务将打印" Hello World"。
运行Grunt任务
保存Gruntfile.js文件的内容并打开终端,然后运行以下命令以打印问候消息" Hello World"。
$grunt greetings
-MacBook-Pro:grunt-project $grunt greetings Running "greetings" task Hello World Done. -MacBook-Pro:grunt-project $
恭喜你!您已经成功创建并执行了Grunt任务。
让我们创建另一个任务
打开Gruntfile.js文件,并添加以下代码以创建新任务。
当grunt运行此任务时,它将打印" Hello"。
module.exports = function(grunt) {
/**
* this will print "Hello World"
* when we run
* $grunt greetings
* on command line
*/
grunt.registerTask("greetings", function() {
console.log("Hello World");
});
/**
* this is the 2nd task
*/
grunt.registerTask("hello", function() {
console.log("Hello");
});
};
现在要运行新任务,请打开终端并输入以下命令。
$grunt hello
-MacBook-Pro:grunt-project $grunt hello Running "hello" task Hello Done. -MacBook-Pro:grunt-project $
合并任务
因此,从上面的示例中可以看到,当我们执行grunt greetings时,grunt将运行Greetings任务。
当我们输入grunt hello时,它将运行hello任务。
通过在Gruntfile.js文件中添加以下代码行,我们可以将两个任务组合在一起使用一个名称(例如mytasks)。
grunt.registerTask("mytasks", ["greetings", "hello"]);
在上面的代码行中,我们创建了一个任务" mytasks",并向其中添加了" greetings"和" hello"任务。
因此,当我们在终端中运行此任务时,grunt将同时运行这两个任务。
我们的最终代码将如下所示。
module.exports = function(grunt) {
/**
* this will print "Hello World"
* when we run
* $grunt greetings
* on command line
*/
grunt.registerTask("greetings", function() {
console.log("Hello World");
});
/**
* this is the 2nd task
*/
grunt.registerTask("hello", function() {
console.log("Hello");
});
/**
* combining the two tasks under one name
* "mytasks"
*/
grunt.registerTask("mytasks", ["greetings", "hello"]);
};
运行组合任务
在终端中,执行以下命令以运行组合任务" mytasks"。
$grunt mytasks
-MacBook-Pro:grunt-project $grunt mytasks Running "greetings" task Hello World Running "hello" task Hello Done. -MacBook-Pro:grunt-project $
创建默认任务
有一种更简单的方法可以用一个名称将任务组合在一起,即创建默认任务。
在下面的示例中,我们将创建一个默认任务,并将问候和问候任务组合到该默认任务下。
grunt.registerTask("default", ["greetings", "hello"]);
Gruntfile.js文件中的最终代码。
module.exports = function(grunt) {
/**
* this will print "Hello World"
* when we run
* $grunt greetings
* on command line
*/
grunt.registerTask("greetings", function() {
console.log("Hello World");
});
/**
* this is the 2nd task
*/
grunt.registerTask("hello", function() {
console.log("Hello");
});
/**
* combining the two tasks under one name
* "mytasks"
*/
grunt.registerTask("mytasks", ["greetings", "hello"]);
/**
* this is the default task
* to run this task just type
* $grunt
*/
grunt.registerTask("default", ["greetings", "hello"]);
};
运行默认任务
要运行默认任务,只需在终端中执行grunt命令。
$grunt
-MacBook-Pro:grunt-project $grunt Running "greetings" task Hello World Running "hello" task Hello Done. -MacBook-Pro:grunt-project $

