Grunt - Creazione di attività

In questo capitolo, impariamo a creare attività . Ogni volta che esegui Grunt, vengono specificate una o più attività da eseguire che notificano a Grunt cosa vorresti che facesse. Se si specifica l' attività predefinita , verrà eseguita per impostazione predefinita.

Attività alias

Ogni volta che viene specificato un elenco di attività, una o più altre attività possono essere sottoposte ad alias da una nuova attività. L'esecuzione dell'alias eseguirà a sua volta tutte le attività specificate in taskList . L' argomento taskList dovrebbe essere un array di attività come mostrato di seguito:

grunt.registerTask(taskName, [description, ] taskList)

Ad esempio, quando si definisce un taskList con attività jshint , concat e uglify e si specifica taskName come predefinito , tutte le attività elencate verranno eseguite automaticamente se Grunt viene eseguito senza specificare alcuna attività.

grunt.registerTask('default', ['jshint', 'concat', 'uglify']);

È inoltre possibile specificare gli argomenti dell'attività come mostrato di seguito:

grunt.registerTask('dist', ['concat:dist', 'uglify:dist']);

Nell'attività precedente, l'alias dist esegue sia le attività concat sia quelle uglify .

Multi Tasks

Ogni volta che esegui più attività, Grunt cerca una proprietà con lo stesso nome nella configurazione di Grunt. Queste attività possono avere più configurazioni, che verranno definite utilizzando destinazioni con nomi arbitrari .

Quando si specificano sia un'attività che una destinazione, verrà elaborata solo la configurazione della destinazione specificata.

grunt concat:foo

Il comando precedente eseguirà solo il foo di destinazione .

Quando si specifica solo un'attività, verranno elaborati tutti i target.

grunt concat

Il comando precedente itererà su tutti gli obiettivi dell'attività concatenata .

Quando si rinomina un'attività con grunt.task.renameTask , Grunt cerca una proprietà con un nuovo nome di attività nell'oggetto config.

grunt.initConfig({
   log: {
      foo: [1, 2, 3],
      bar: 'Welcome to tutorialspoint',
      sap: true
   }
});

grunt.registerMultiTask('log', 'Log stuff.', function() {
   grunt.log.writeln(this.target + ': ' + this.data);
});

Nell'esempio precedente, multi task registrerà foo: 1,2,3 se Grunt è stato eseguito tramite grunt log: foo o registrerà bar: Benvenuto in tutorialspoint ogni volta che verrà eseguito attraverso grunt log: bar . Registrerà foo: 1,2,3 quindi bar: Welcome to tutorialspoint quindi sap: true quando Grunt viene eseguito come registro grugnito .

Attività di base

Ogni volta che esegui un'attività di base, Grunt non cercherà la configurazione o l'ambiente. Invece esegue la funzione task che è specificata, passa tutti gli argomenti separati da due punti specificati in come argomenti della funzione.

grunt.registerTask(taskName, [description, ] taskFunction)

Nell'esempio seguente, l'attività registra foo, testando 123 se Grunt viene eseguito tramite il comando grunt foo: testing: 123 . Ogni volta che l'attività viene eseguita senza argomenti come grugnito foo , l'attività registrerà foo, senza argomenti .

grunt.registerTask('foo', 'A simple task to logs stuff.', function(arg1, arg2) {
   if (arguments.length === 0) {
      grunt.log.writeln(this.name + ", no args");
   } else {
      grunt.log.writeln(this.name + ", " + arg1 + " " + arg2);
   }
});

Attività personalizzate

Se non vuoi seguire la struttura multi-task , puoi definire la tua attività personalizzata come mostrato di seguito -

grunt.registerTask('default', 'My "default" task description.', function() {
  grunt.log.writeln('Currently running the "default" task.');
});

È possibile eseguire un'attività all'interno di un'altra attività come mostrato di seguito:

grunt.registerTask('foo', 'My "foo" task.', function() {
   // Enqueue bar and baz tasks, to run after foo completes, in-order.
   grunt.task.run('bar', 'baz');
   // Or:
   grunt.task.run(['bar', 'baz']);
});

Puoi anche creare attività asincrone come mostrato di seguito:

grunt.registerTask('asyncfoo', 'My "asyncfoo" task.', function() {
   // Force task into async mode and grab a handle to the done() function.
   var done = this.async();
   // Run some sync stuff.
   grunt.log.writeln('Processing your task..');
   // Run some async stuff.
   setTimeout(function() {
      grunt.log.writeln('Finished!');
      done();
   }, 1000);
});

È possibile creare attività che possono accedere al loro nome e argomenti come mostrato di seguito:

grunt.registerTask('foo', 'My task "foo" .', function(a, b) {
   grunt.log.writeln(this.name, a, b);
});

// Usage:
// grunt foo
//   logs: "foo", undefined, undefined
// grunt foo:bar
//   logs: "foo", "bar", undefined
// grunt foo:bar:baz
//   logs: "foo", "bar", "baz"

È possibile creare l'attività in modo tale che, ogni volta che vengono registrati errori, le attività possono fallire come mostrato di seguito:

grunt.registerTask('foo', 'My task "foo" .', function() {
   if (failureOfSomeKind) {
      grunt.log.error('This is an error message.');
   }

   // If this task had errors then fail by returning false
   if (ifErrors) { return false; }

   grunt.log.writeln('This is success message');
});

Ogni volta che un'attività fallisce, ogni attività successiva verrà terminata a meno che non sia stato specificato --force .

grunt.registerTask('foo', 'My task "foo" .', function() {
   // Fail synchronously.
   return false;
});

grunt.registerTask('bar', 'My task "bar" .', function() {
   var done = this.async();
   setTimeout(function() {
      // Fail asynchronously.
      done(false);
   }, 1000);
});

Le attività possono dipendere da altre attività per l'esecuzione corretta. Ricorda che grunt.task.requires non eseguirà effettivamente altre attività, ma controllerà solo se è stato eseguito e non è fallito.

grunt.registerTask('foo', 'My task "foo" .', function() {
   return false;
});

grunt.registerTask('bar', 'My task "bar" .', function() {
   // Fail task if foo task failed or never ran.
   grunt.task.requires('foo');
   // This code executes if the foo task executed successfully.
   grunt.log.writeln('Hello, World.. Welcome to Tutorialspoint!..');
});

// Usage:
// grunt foo bar doesn't log, because foo failed to execute.
// **Note: This is an example of space-separated sequential commands,
// (similar to executing two lines of code: `grunt foo` then `grunt bar`)
// grunt bar doesn't log, because foo never ran.

Le attività possono anche fallire ogni volta che le proprietà di configurazione richieste non vengono trovate.

grunt.registerTask('foo', 'My task "foo" .', function() {
   // Fail task if meta.name config properties is missing
   // Format 1: String 
   grunt.config.requires('meta.name');
   // or Format 2: Array
   grunt.config.requires(['meta', 'name']);
   // Log... conditionally.
   grunt.log.writeln('This only log if meta.name is defined in the config.');
});

Le attività possono accedere alle proprietà di configurazione come mostrato di seguito:

grunt.registerTask('foo', 'My task "foo" .', function() {
   // Log the value of the property. Returns null if the property is undefined.
   grunt.log.writeln('The meta.name property is: ' + grunt.config('meta.name'));
   // Also logs the value of the property. Returns null if the property is undefined.
   grunt.log.writeln('The meta.name property is: ' + grunt.config(['meta', 'name']));
});