不使用Grunt.initConfig()注册Grunt任务

Register Grunt tasks without grunt.initConfig()

本文关键字:Grunt 注册 任务 initConfig      更新时间:2023-09-26

我希望我的gruntfile.js具有自然的结构,以便微任务一个接一个地执行。假设我有以下结构:

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: {
        movedTyping: 'options...'
    },
    copy: {
        typing: 'options...',
        lessVariables: 'options...',
        html: 'options...'
    },
    less: {
        compile: 'options...'
    },
    typescript: {
        compile: 'options...'
    }
});

grunt.registerTask('build', [
    // TYPESCRIPT
    'typescript:compileSingle',
    'copy:typing',
    'clean:movedTyping',
    // LESS
    'less:compile',
    'copy:lessVariables',
    // HTML
    'copy:html'
]);

但我想实现另一种结构:

grunt.registerTask('build', function () {
    // TYPESCRIPT
    grunt.task.run('typescript', 'options...');
    grunt.task.run('copy', 'options...');
    grunt.task.run('clean', 'options...');
    // LESS
    grunt.task.run('less', 'options...');
    grunt.task.run('copy', 'options...');
    // HTML
    grunt.task.run('copy', 'options...');
});

如何?

您可以使用设置对象的属性。(点)符号。因此也可以设置嵌套结构数据。我还没有遇到更干净的方法,我很高兴看到更好的方法。

grunt.registerTask('build', function () {
   // TYPESCRIPT
   grunt.config.set('typescript.compile','<options>');
   grunt.task.run('typescript');
   ......................
});

为了实现这一点,我创建了NPM模块创建了grunt任务。现在我的咕哝文件看起来是这样的:

// Gruntfile.js 
module.exports = function (grunt) {
    require('create-grunt-tasks')(grunt, function (create) {
        create.task('build')
            // Compile TypeScript and move typing 
            .sub('typescript', {
                src: 'src/index.ts',
                dest: 'build/index.js',
                options: { module: 'amd', target: 'es5', declaration: true }
            })
            .sub('copy', {
                expand: true, flatten: true,
                src: 'build/index.d.ts',
                dest: 'build/typing/index.d.ts'
            })
            .sub('clean', ['build/index.d.ts'])
            // Copy HTML 
            .sub('copy', {
                expand: true, flatten: true,
                src: 'src/index.html',
                dest: 'build/index.html'
            });
    });
}