Grunt: custom task development how-to

2019-04-06 22:49发布

问题:

I need to implement a custom Grunt task and I'm absolutely lost about the development workflow.

  1. How do I develop a custom task and I simulate loading it using npm during development?
  2. Is there any other way of distributing custom tasks instead of using npm? I mean, can I distribute a JavaScript file defining the whole custom Grunt task and import it in the Gruntfile.js directly?

Since the whole task would be in a very early development stage, maybe the effort of publishing it in npm isn't a good idea.

Thanks in advance.

回答1:

custom grunt tasks are basically node-modules which you can publish to the npm registry. take a look at existing ones, and the documentation how to build them here:

http://gruntjs.com/api/grunt.task

basically you just do something like this:

module.exports = function (grunt) {

  // or use grunt.registerMultiTask
  grunt.registerTask('your-taskname', 'your task description', function () {
  });
};

to make it easy for you, you should use grunt-init with the grunt-init-gruntplugin which basically sets everything up for you!

if you dont want to publish your module to npm, you can install it in in your project from a git repository (for example using github):

$ npm install git+https://github.com/your-user/your-repository --save

the --save option saves it automatically as a dependency into projects package.json.

if you just want to include a single js file in your project with your task, put that in a directory of your choice (i use grunt-tasks here), and include it in your gruntfile like that:

grunt.loadTasks("./grunt-tasks");

that will try to include every js-file in that directory as grunt tasks.